This problem can be efficiently solved using a counting approach combined with enumeration. The core idea is to first count the number of black pixels ('B') in each row and each column. Then, we iterate through the matrix again. If a pixel is black and its row and column counts are both 1 (meaning it's the only black pixel in that row and column), we increment the count of lonely pixels.
Algorithm:
Initialization:
rows
and cols
, to store the counts of black pixels in each row and column, respectively. Initialize all elements to 0. The size of rows
will be the number of rows in the picture, and the size of cols
will be the number of columns.Counting Black Pixels:
picture
matrix. For each pixel:
rows
(for the row) and cols
(for the column).Counting Lonely Pixels:
picture
matrix again. For each pixel:
rows[i]
(the count of black pixels in its row) is 1 and cols[j]
(the count of black pixels in its column) is 1, then increment the ans
(the count of lonely pixels).Return Result:
ans
.Time Complexity: O(m*n) - We iterate through the matrix twice, where 'm' is the number of rows and 'n' is the number of columns.
Space Complexity: O(m+n) - We use two arrays (rows
and cols
) whose sizes are proportional to the number of rows and columns in the input matrix.
Code Examples (with explanations inline):
The provided code examples in Python, Java, C++, Go, and TypeScript all follow this algorithm. Let's highlight the key parts of the Python solution:
class Solution:
def findLonelyPixel(self, picture: List[List[str]]) -> int:
rows = [0] * len(picture) # Initialize row counts
cols = [0] * len(picture[0]) # Initialize column counts
# Count black pixels in each row and column
for i, row in enumerate(picture):
for j, x in enumerate(row):
if x == "B":
rows[i] += 1
cols[j] += 1
ans = 0 # Initialize lonely pixel count
# Count lonely pixels
for i, row in enumerate(picture):
for j, x in enumerate(row):
if x == "B" and rows[i] == 1 and cols[j] == 1:
ans += 1
return ans
The other language examples follow the same structure, just using their respective syntax and data structures. The key is the two counting loops and the final loop that checks for the lonely pixel condition.