# 531. Lonely Pixel I     • Time: $O(mn)$
• Space: $O(m + n)$
  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 class Solution { public: int findLonelyPixel(vector>& picture) { const int m = picture.size(); const int n = picture.size(); int ans = 0; vector rows(m); // rows[i] := # of Bs in rows i vector cols(n); // cols[i] := # of Bs in cols i for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (picture[i][j] == 'B') { ++rows[i]; ++cols[j]; } for (int i = 0; i < m; ++i) if (rows[i] == 1) // Only have to examine the rows when rows[i] == 1 for (int j = 0; j < n; ++j) // After we met the 'B' in this rows, we break and search the next row if (picture[i][j] == 'B') { if (cols[j] == 1) ++ans; break; } return ans; } }; 
  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 class Solution { public int findLonelyPixel(char[][] picture) { final int m = picture.length; final int n = picture.length; int ans = 0; int[] rows = new int[m]; // rows[i] := # of Bs in rows i int[] cols = new int[n]; // cols[i] := # of Bs in cols i for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (picture[i][j] == 'B') { ++rows[i]; ++cols[j]; } for (int i = 0; i < m; ++i) if (rows[i] == 1) // Only have to examine the rows when rows[i] == 1 for (int j = 0; j < n; ++j) // After we met the 'B' in this rows, we break and search the next row if (picture[i][j] == 'B') { if (cols[j] == 1) ++ans; break; } return ans; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Solution: def findLonelyPixel(self, picture: List[List[str]]) -> int: m = len(picture) n = len(picture) ans = 0 rows =  * m # rows[i] := # of Bs in rows i cols =  * n # cols[i] := # of Bs in cols i for i in range(m): for j in range(n): if picture[i][j] == 'B': rows[i] += 1 cols[j] += 1 for i in range(m): if rows[i] == 1: # Only have to examine the rows when rows[i] == 1 for j in range(n): # After we met the 'B' in this rows, we break and search the next row if picture[i][j] == 'B': if cols[j] == 1: ans += 1 break return ans