Problem Description
Given an m x n picture consisting of black ('B') and white ('W') pixels, return the number of black lonely pixels. A black lonely pixel is defined as a 'B' that is the only 'B' in both its row and its column.
Key Insights
- Count the number of 'B' pixels in each row.
- Count the number of 'B' pixels in each column.
- A pixel is considered lonely if the count in its corresponding row and column is exactly 1.
- Two passes through the matrix can efficiently solve the problem: one for counting and one for checking conditions.
Space and Time Complexity
Time Complexity: O(m * n), where m and n are the dimensions of the picture. Space Complexity: O(m + n), used to store the row and column counts.
Solution
The solution works by first scanning the entire matrix to compute the number of black pixels in each row and each column using two arrays/lists. Once these counts are available, a second pass through the matrix determines for each black pixel if it is lonely by checking if its corresponding row and column count equals 1. The approach uses simple array data structures for tallying counts and ensures that each element is processed only a constant number of times.