Skip to content

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<vector<char>>& picture) {
    const int m = picture.size();
    const int n = picture[0].size();
    int ans = 0;
    vector<int> rows(m);  // rows[i] := the number of B's in rows i
    vector<int> cols(n);  // cols[i] := the number of B's 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 if rows[i] == 1.
        for (int j = 0; j < n; ++j)
          // After meeting a 'B' in this rows, 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[0].length;
    int ans = 0;
    int[] rows = new int[m]; // rows[i] := the number of B's in rows i
    int[] cols = new int[n]; // cols[i] := the number of B's 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 if rows[i] == 1.
        for (int j = 0; j < n; ++j)
          // After meeting a 'B' in this rows, 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[0])
    ans = 0
    rows = [0] * m  # rows[i] := the number of B's in rows i
    cols = [0] * n  # cols[i] := the number of B's 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 if rows[i] == 1.
        for j in range(n):
          # After meeting a 'B' in this rows, break and search the next row.
          if picture[i][j] == 'B':
            if cols[j] == 1:
              ans += 1
            break

    return ans