首页 > 代码库 > 531. Lonely Pixel I
531. Lonely Pixel I
Given a picture consisting of black and white pixels, find the number of black lonely pixels.
The picture is represented by a 2D char array consisting of ‘B‘ and ‘W‘, which means black and white pixels respectively.
A black lonely pixel is character ‘B‘ that located at a specific position where the same row and same column don‘t have any other black pixels.
Example:
Input: [[‘W‘, ‘W‘, ‘B‘], [‘W‘, ‘B‘, ‘W‘], [‘B‘, ‘W‘, ‘W‘]] Output: 3 Explanation: All the three ‘B‘s are black lonely pixels.
Note:
- The range of width and height of the input 2D array is [1,500].
本题有点类似于皇后问题,思路是,第一遍找出有B的字符,然后把它的行和列分别+1,第二遍遍历的时候,找出有B的字符并且,行和列都是1的字符,count++;
代码如下:
1 public class Solution { 2 public int findLonelyPixel(char[][] picture) { 3 int count = 0; 4 int row = picture.length; 5 int col = picture[0].length; 6 int[] rows = new int[row]; 7 int[] cols = new int[col]; 8 for(int i=0;i<row;i++){ 9 for(int j=0;j<col;j++){ 10 if(picture[i][j]==‘B‘){ 11 rows[i]++; 12 cols[j]++; 13 } 14 } 15 } 16 for(int i=0;i<row;i++){ 17 for(int j=0;j<col;j++){ 18 if(picture[i][j]==‘B‘&&rows[i]==1&&cols[j]==1){ 19 count++; 20 } 21 } 22 } 23 return count; 24 } 25 }
531. Lonely Pixel I
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。