# Simple Java AC Solution

•   public int findLonelyPixel(char[][] picture) {
int count = 0;
if(picture.length<1){
return count;
}
//Find black pixel in matrixx
for(int row=0; row<picture.length; row++){
for(int col=0; col<picture[0].length; col++){
if(picture[row][col]=='B'){
if(isLonely(row, col, picture)){
count++;
}
}
}
}
return count;
}

// Check in four directions.
private boolean isLonely(int row, int col, char[][] picture){
int saveR = row;
int saveC = col;
// check left direction
row--;
while(row>=0){
if( picture[row][col] =='B'){
return false;
}
row--;
}

row = saveR;
col = saveC;
row++;
// check right direction
while(row<picture.length){
if( picture[row][col] =='B'){
return false;
}
row++;
}

row = saveR;
col = saveC;
col--;
// check up direction
while(col>=0){
if( picture[row][col] =='B'){
return false;
}
col--;
}

row = saveR;
col = saveC;
col++;
// check up direction
while(col<picture[0].length){
if( picture[row][col] =='B'){
return false;
}
col++;
}
return true;
}

• My solution: first find out lonely_rows and lonely_columns, which contain only 1 black pixel, then scan the picture again, count black pixels whose (r, c) are in lonely_rows and lonely_columns :)

class Solution(object):
def findLonelyPixel(self, picture):
"""
:type picture: List[List[str]]
:rtype: int
"""
row_to_black_count = collections.defaultdict(int)
col_to_black_count = collections.defaultdict(int)
for r_idx, row in enumerate(picture):
for c_idx, pixel in enumerate(row):
if pixel == 'B':
row_to_black_count[r_idx] += 1
col_to_black_count[c_idx] += 1
lonely_row = {k for k, v in row_to_black_count.iteritems() if v == 1}
lonely_col = {k for k, v in col_to_black_count.iteritems() if v == 1}

lonely_black = 0
for r_idx, row in enumerate(picture):
for c_idx, pixel in enumerate(row):
if pixel == 'B' and r_idx in lonely_row and c_idx in lonely_col:
lonely_black += 1
return lonely_black

Also check this one-liner, wu ti tou di...

• @kitt Thanks for sharing your solution~!
Java version attached below

public int findLonelyPixel(char[][] picture) {
//Traverse whole tree accumulating Black in each row and col
int[] rowAccumulate = new int[picture.length];
int[] colAccumulate = new int[picture[0].length];
for(int i=0; i<picture[0].length; i++){
for(int j=0; j<picture.length; j++){
if(picture[j][i]=='B'){
rowAccumulate[j] += 1;
colAccumulate[i] += 1;
}
}
}
int count=0;
//Traverse whole tree check each Black if in both lonely row and col
for(int i=0; i<picture[0].length; i++){
for(int j=0; j<picture.length; j++){
if(picture[j][i]=='B' && rowAccumulate[j]==1 && colAccumulate[i]==1){
count++;
}
}
}
return count;

}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.