LeetCode in Python 531. Lonely Pixel

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].

Solution: (未测试)

def lonelyPixel(self, grid):
  rows, cols = len(grid), len(grid[0])
  rowCount, colCount = [0 for i in range(rows)], [0 for i in range(cols)]
  res = ['#' for i in range(rows)]

  for i in range(rows):
    for j in range(cols):
      if grid[i][j] == 'W': continue
      res[i] = '#' if rowCount[i] or colCount[j] else j
      rowCount[i] += 1
      colCount[j] += 1

  count = 0
  for c in res:
    if c != '#':
      count++

  return count

n^2复杂度,遍历grid一次即可。res里存可能的结果,遍历时更新。

posted @ 2019-07-16 13:57  bossman  阅读(241)  评论(0编辑  收藏  举报