requirements
I give you a picture of size m x N, the picture is composed of black and white pixels, ‘B’ represents black pixels, ‘W’ represents white pixels, please count and return the number of black lonely pixels.
Black lonely pixel is defined as: if there is no other black pixel in the same row and column of black pixel ‘B’, then the black pixel is black lonely pixel.
Example 1:
Input: picture = [[" W ", "W", "B"], [" W ", "B", "W"], [" B ", "W", "W"]] output: 3: all three 'B' is black pixels of lonelinessCopy the code
Example 2:
Input: picture = [[" B ", "B", "B"], [" B ", "B", "W"], [" B ", "B", "B"]] output: 0Copy the code
The core code
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" andx! = x0:return False
for y in range(n):
if picture[x0][y] == "B" andy ! = 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
Copy the code
We encapsulate a function to check if there are other “B” s in the row and column at this position. If there are other “B” s in the row and column at this position, return False, if there are other “B” s in the column at this position, return True if there are other “B” s in the column at this position.