给定一幅黑白像素组成的图像, 计算黑色孤独像素的数量。
图像由一个由‘B’和‘W’组成二维字符数组表示, ‘B’和‘W’分别代表黑色像素和白色像素。
黑色孤独像素指的是在同一行和同一列不存在其他黑色像素的黑色像素。
示例:
输入: [['W', 'W', 'B'], ['W', 'B', 'W'], ['B', 'W', 'W']] 输出: 3 解析: 全部三个'B'都是黑色孤独像素。
注意:
- 输入二维数组行和列的范围是 [1,500]。
数组或哈希表统计每一行、每一列中 'B' 出现的次数。
class Solution:
def findLonelyPixel(self, picture: List[List[str]]) -> int:
m, n = len(picture), len(picture[0])
rows, cols = [0] * m, [0] * n
for i in range(m):
for j in range(n):
if picture[i][j] == 'B':
rows[i] += 1
cols[j] += 1
res = 0
for i in range(m):
if rows[i] == 1:
for j in range(n):
if picture[i][j] == 'B' and cols[j] == 1:
res += 1
break
return res
class Solution {
public int findLonelyPixel(char[][] picture) {
int m = picture.length, n = picture[0].length;
int[] rows = new int[m];
int[] cols = new int[n];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (picture[i][j] == 'B') {
++rows[i];
++cols[j];
}
}
}
int res = 0;
for (int i = 0; i < m; ++i) {
if (rows[i] == 1) {
for (int j = 0; j < n; ++j) {
if (picture[i][j] == 'B' && cols[j] == 1) {
++res;
break;
}
}
}
}
return res;
}
}
class Solution {
public:
int findLonelyPixel(vector<vector<char>>& picture) {
int m = picture.size(), n = picture[0].size();
vector<int> rows(m);
vector<int> cols(n);
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (picture[i][j] == 'B')
{
++rows[i];
++cols[j];
}
}
}
int res = 0;
for (int i = 0; i < m; ++i)
{
if (rows[i] == 1)
{
for (int j = 0; j < n; ++j)
{
if (picture[i][j] == 'B' && cols[j] == 1)
{
++res;
break;
}
}
}
}
return res;
}
};
func findLonelyPixel(picture [][]byte) int {
m, n := len(picture), len(picture[0])
rows := make([]int, m)
cols := make([]int, n)
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if picture[i][j] == 'B' {
rows[i]++
cols[j]++
}
}
}
res := 0
for i := 0; i < m; i++ {
if rows[i] == 1 {
for j := 0; j < n; j++ {
if picture[i][j] == 'B' && cols[j] == 1 {
res++
break
}
}
}
}
return res
}