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.

Example:

Input: 
[['W', 'W', 'B'],
 ['W', 'B', 'W'],
 ['B', 'W', 'W']]

Output: 3
Explanation: All the three 'B's are black lonely pixels.

Note:

  1. The range of width and height of the input 2D array is [1,500].
 1 public class Solution {
 2     public int findLonelyPixel(char[][] picture) {
 3         if (picture == null || picture[0] == null) return 0;
 4         
 5         int m = picture.length, n = picture[0].length;
 6         boolean[] rows = new boolean[m];
 7         Arrays.fill(rows, true);
 8         boolean[] cols = new boolean[n];
 9         Arrays.fill(cols, true);
10         
11         for (int i = 0; i < m; i++) {
12             int rowCount = 0;
13             for (int j = 0; j < n; j++) {
14                 if (picture[i][j] == 'B')
15                     rowCount++;
16             }
17             if (rowCount > 1) rows[i] = false;
18         }
19         
20         for (int j = 0; j < n; j++) {
21             int colCount = 0;
22             for (int i = 0; i < m; i++) {
23                 if (picture[i][j] == 'B')
24                     colCount++;
25             }
26             if (colCount > 1) cols[j] = false;
27         }
28         
29         int result = 0;
30         for (int i = 0; i < m; i++) {
31             for (int j = 0; j < n; j++) {
32                 if (picture[i][j] == 'B' && rows[i] && cols[j])
33                     result++;
34             }
35         }
36         return result;
37     }
38 }
原文地址:https://www.cnblogs.com/amazingzoe/p/6661168.html