LeetCode 531. Lonely Pixel I (Medium)

Description:

Given a picture consisting of black and white pixels, find the number of black lonely pixels.

The picture is represented by a 2D char array consisting of ‘B’ and ‘W’, which means black and white pixels respectively.

A black lonely pixel is character ‘B’ that located at a specific position where the same row and same column don’t have any other black pixels.

Example:
Input: 
[['W', 'W', 'B'],
 ['W', 'B', 'W'],
 ['B', 'W', 'W']]

Output: 3
Explanation: All the three 'B's are black lonely pixels.
Note:
  1. The range of width and height of the input 2D array is [1,500].

Analysis:
  1. Define two arrays rows  and columns, the lengths of which are picture.length  picture[0].length  respectively and the default values of which are all -1. The array rows  is used to record the column index of the only 'W'  element for each row while the array columns  is used to record the row index of the only 'W'  element for each column.
  2. We use a nested loop to traverse the given 2D array. For every row, if the row has exactly one 'W'  element, then we assign the column index of this element j  to row[i], if the row has more than two 'W'  elements, we assign -2  to row[i]. Likewise, for every column, if the column has exactly one ‘W’ element, we assign the row index of this element i  to column[j], if the column has exactly two 'W'  elements, we assign -2  to column[j].
  3. For each element rows[i]  in the array rows, if rows[i]  is larger than -1  and columns[rows[i]]  is equal to i, it means the only W  element in row with index i  and the only W  element in column with index rows[i]  is the same element. Namely, this element with index (i, rows[i])&nbsp is a lonely pixel.

Code:
class Solution {
    public int findLonelyPixel(char[][] picture) {
        int M = picture.length;
        int N = picture[0].length;
        int[] rows = new int[M];
        int[] columns = new int[N];
        
        
        // initialize
        for(int i = 0; i < M; i++) {
            rows[i] = -1;
        }
        
        for(int j = 0; j < N; j++) {
            columns[j] = -1;
        }
        
        for(int i = 0; i < M; i++) {
            for(int j = 0; j < N; j++) {
                if(picture[i][j] == 'B') {
                    rows[i] = rows[i] == -1 ? j : -2;
                    columns[j] = columns[j] == -1 ? i : -2;
                }
            }
        }
        
        int sum = 0;
        for(int i = 0; i < M; i++) {
            if(rows[i] >= 0 && columns[rows[i]] == i) {
                sum += 1;
            }
        }
        
        return sum;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值