【array-java】531. Lonely Pixel I

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:

The range of width and height of the input 2D array is [1,500].

answer one

给一个只含有黑白像素的图片,找出黑色孤独像素的数量。黑色孤独像素是这个像素所在的行和列都不含有黑色像素。

最基本的想法就是找出每一个黑色像素,然后对相应的行和列进行检查,看是否含有黑色像素。但这种方法肯定含有重复操作,效率肯定不高。

解法:利用数组rows,cols分别记录某行、某列’B’像素的个数。然后遍历一次picture找到符合条件的。

public int findLonelyPixel(char[][] picture) {
    int n = picture.length, m = picture[0].length;
     
    int[] rowCount = new int[n], colCount = new int[m];
    for (int i=0;i<n;i++)
        for (int j=0;j<m;j++)
            if (picture[i][j] == 'B') { rowCount[i]++; colCount[j]++; }
 
    int count = 0;
    for (int i=0;i<n;i++)
        for (int j=0;j<m;j++)
            if (picture[i][j] == 'B' && rowCount[i] == 1 && colCount[j] == 1) count++;
                 
    return count;
}

answer two

Java: DFS

public int findLonelyPixel(char[][] picture) {
    int numLone = 0;
    for (int row = 0; row < picture.length; row++) {
        for (int col = 0; col < picture[row].length; col++) {
            if (picture[row][col] == 'W') {
                continue;
            }
            if (dfs(picture, row - 1, col, new int[] {-1, 0}) && dfs(picture, row + 1, col, new int[] {1, 0})
             && dfs(picture, row, col - 1, new int[] {0, -1}) && dfs(picture, row, col + 1, new int[] {0, 1})) {
                numLone++;
            }
        }
    }
    return numLone;
}
 
// use dfs to find if current pixel is lonely
private boolean dfs(char[][] picture, int row, int col, int[] increase) {
    // base case
    if (row < 0 || row >= picture.length || col < 0 || col >= picture[0].length) {
        return true;
    } else if (picture[row][col] == 'B') {
        return false;
    }
    // recursion
    return dfs(picture, row + increase[0], col + increase[1], increase);
}    

参考

answer three

思路:
可以记录下每个黑点的位置,以及每行、每列出现的黑点的个数。然后遍历每个黑点,如果发现它所在的行和列的黑点数都为1,那么它就是孤立黑点了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值