[LeetCode]Lonely Pixel I

题目描述:

LeetCode 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:

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

题目大意:

给定一个包含字符'W'(白色)和'B'(黑色)的像素矩阵picture。

求所有同行同列有且仅有一个'B'像素的像素个数。

注意:

二维数组的宽度和高度在范围[1,500]之间。

解题思路:

利用数组rows,cols分别记录某行、某列'B'像素的个数。

然后遍历一次picture即可。

Python代码:

class Solution(object):
    def findLonelyPixel(self, picture):
        """
        :type picture: List[List[str]]
        :rtype: int
        """
        w, h = len(picture), len(picture[0])
        rows, cols = [0] * w, [0] * h
        for x in range(w):
            for y in range(h):
                if picture[x][y] == 'B':
                    rows[x] += 1
                    cols[y] += 1
        ans = 0
        for x in range(w):
            for y in range(h):
                if picture[x][y] == 'B':
                    if rows[x] == 1:
                        if cols[y] == 1:
                            ans += 1
        return ans

 

本文链接:http://bookshadow.com/weblog/2017/03/05/leetcode-lonely-pixel-i/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论