leetcode_531 孤独像素 I

1,140 阅读1分钟

要求

给你一个大小为 m x n 的图像 picture ,图像由黑白像素组成,'B' 表示黑色像素,'W' 表示白色像素,请你统计并返回图像中 黑色 孤独像素的数量。

黑色孤独像素 的定义为:如果黑色像素 'B' 所在的同一行和同一列不存在其他黑色像素,那么这个黑色像素就是黑色孤独像素。

示例 1:

image.png

输入:picture = [["W","W","B"],["W","B","W"],["B","W","W"]]
输出:3
解释:全部三个 'B' 都是黑色的孤独像素

示例 2:

image.png

输入:picture = [["B","B","B"],["B","B","W"],["B","B","B"]]
输出:0

核心代码

class Solution:
    def findLonelyPixel(self, picture: List[List[str]]) -> int:
        if not picture or not picture[0]:
            return 0
        m,n = len(picture),len(picture[0])
        res = 0

        def check(x0,y0):
            for x in range(m):
                if picture[x][y0] == "B" and x!= x0:
                    return False
            for y in range(n):
                if picture[x0][y] == "B" and y != y0:
                    return False
            return True

        for i in range(m):
            for j in range(n):
                if picture[i][j] == "B" and check(i,j):
                    res +=1 
        return res

image.png

解题思路:就是我们封装了一个函数,来检查这个位置的行和列中是不是存在其他的"B",存在则返回False,不存在则返回True,我们遍历所有的位置,寻找孤独像素,进行数据的累计。