531. Lonely Pixel I

  • 44.4%

https://leetcode.com/contest/leetcode-weekly-contest-22/problems/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.

1
2
3
4
5
6
7
8
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].

cpp


my code:

与第200道,小岛的题目很类似,可以考虑参考。但是有不一样,这里建立两个数组,保证横纵坐标都是1,且此处为‘B’就是要找的点,计数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
int findLonelyPixel(vector<vector<char>>& picture) {
// if(picture==NULL) return 0;
if(picture.size()==0) return 0;
if(picture[0].size()==0) return 0;
int m = picture.size();
int n = picture[0].size();
vector<int> dp1(m, 0);
vector<int> dp2(n, 0);
for(int i=0; i<m; i++){
int tmp = 0;
for(int j=0; j<n; j++){
if(picture[i][j]=='B')
tmp++;
}
dp1[i] = tmp;
}

for(int i=0; i<n; i++){
int tmp = 0;
for(int j=0; j<m; j++){
if(picture[j][i]=='B')
tmp++;
}
dp2[i] = tmp;
}

int res = 0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(dp1[i]==1 && dp2[j]==1 && picture[i][j]=='B')
res++;
}
}
return res;
}
};
谢谢你,可爱的朋友。