Description:
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].
Analysis:
- Define two arrays
rows
andcolumns
, the lengths of which arepicture.length
picture[0].length
respectively and the default values of which are all-1
. The arrayrows
is used to record the column index of the only'W'
element for each row while the arraycolumns
is used to record the row index of the only'W'
element for each column. - We use a nested loop to traverse the given 2D array. For every row, if the row has exactly one
'W'
element, then we assign the column index of this elementj
torow[i]
, if the row has more than two'W'
elements, we assign-2
torow[i]
. Likewise, for every column, if the column has exactly one ‘W’ element, we assign the row index of this elementi
tocolumn[j]
, if the column has exactly two'W'
elements, we assign-2
tocolumn[j]
. - For each element
rows[i]
in the arrayrows
, ifrows[i]
is larger than-1
andcolumns[rows[i]]
is equal toi
, it means the onlyW
element in row with indexi
and the onlyW
element in column with indexrows[i]
is the same element. Namely, this element with index(i, rows[i])
  is a lonely pixel.
Code:
class Solution {
public int findLonelyPixel(char[][] picture) {
int M = picture.length;
int N = picture[0].length;
int[] rows = new int[M];
int[] columns = new int[N];
// initialize
for(int i = 0; i < M; i++) {
rows[i] = -1;
}
for(int j = 0; j < N; j++) {
columns[j] = -1;
}
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
if(picture[i][j] == 'B') {
rows[i] = rows[i] == -1 ? j : -2;
columns[j] = columns[j] == -1 ? i : -2;
}
}
}
int sum = 0;
for(int i = 0; i < M; i++) {
if(rows[i] >= 0 && columns[rows[i]] == i) {
sum += 1;
}
}
return sum;
}
}