Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
def depth_search(self, grid, visit, i, j): stack = [(i,j)] while len(stack) != 0: (m,n) = stack.pop() visit[m][n] = True if m!=0 and grid[m-1][n]=='1' and visit[m-1][n]==False: stack.append((m-1,n)) if n!=0 and grid[m][n-1]=='1' and visit[m][n-1]==False: stack.append((m,n-1)) if m!=len(grid)-1 and grid[m+1][n]=='1' and visit[m+1][n]==False: stack.append((m+1,n)) if n!=len(grid[0])-1 and grid[m][n+1]=='1' and visit[m][n+1]==False: stack.append((m,n+1))
def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ if grid==None or len(grid)==0: return 0 counter = 0 visit = [[False] * len(grid[0]) for i in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j]=='0' or visit[i][j]: continue counter += 1 self.depth_search(grid, visit, i, j) return counter
评论系统未开启,无法评论!