解法
根据题目条件我们知道,最后需要有满足以下条件:
- 相同的行刚好有
N
个(否则含有B
的列就会有超过N
个B
了),此时含有B
的列至少有N
个B
- 这个相同的行得有刚好
N
个B
满足这个条件下的行的含有B
的列里,刚好含有N
个B
的列里的B
就是想求的元素,每有一个这样的列,ans
就会增加N
主要是如何把相同的行归类在一起呢?把每一行搞成一个字符串,可以直接用hash表分类
class Solution(object):
def findBlackPixel(self, picture, N):
"""
:type picture: List[List[str]]
:type N: int
:rtype: int
"""
picture = map(lambda x:"".join(x), picture)
m = len(picture)
n = len(picture[0])
col = [0]*n
for j in xrange(n):
for i in xrange(m):
if picture[i][j]=='B':
col[j] += 1
from collections import defaultdict
cnt = defaultdict(int)
for s in picture:
if len(filter(lambda x:x=='B', s))==N:
cnt[s] += 1
ans = 0
for s,cnt in cnt.iteritems():
if cnt!=N:continue
for j in xrange(n):
if s[j]=='B' and col[j]==N:
ans += N
return ans