题目:https://www.lintcode.com/problem/number-of-islands/description
思想:使用 bfs 搜索整个二维数组grid ,建立一个二维状态数组self.result记录此位置是否已经访问。尽可能多定义函数实现略复杂的功能 ,以保证主函数的逻辑清晰。(仅通过94%cases/超时)
class Solution:
"""
@param grid: a boolean 2D matrix
@return: an integer
"""
def numIslands(self, grid):
# write your code here
count = 0
self.lenx = len(grid)
if grid is None or self.lenx == 0:
return count
self.leny = len(grid[0])
# build a matrix with visited status
self.result = [[False for x in range(self.leny)] for y in range(self.lenx)]
for w in range(self.lenx):
for u in range(self.leny):
if self.check(grid,w,u):
self.bfshelper(grid,w,u)
count += 1
return count
def check(self,grid,x,y):
if x >= 0 and y >= 0 and x < self.lenx and y < self.leny and grid[x][y] and (not self.result[x][y]):
return True
return False
def bfshelper(self,grid,x,y):
deltax = [0 ,0 , 1, -1]
deltay = [1 ,-1 ,0 , 0]
queue = [[x,y]]
while queue:
[x,y] = queue.pop(0)
self.result[x][y] = True
for i in range(4):
newx = x + deltax[i]
newy = y + deltay[i]
if self.check(grid, newx, newy):
queue.append((newx, newy))