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.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
DFS 遍历,将1周围的1都变为0,最后数下有多少个1即可。
class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ if not len(grid): return 0 res = 0 m,n = len(grid),len(grid[0]) for i in range(m): for j in range(n): if grid[i][j]=='1': res += 1 self.dfs(grid,i,j,m,n) return res def dfs(self,grid,i,j,m,n): if i<0 or i>=m or j<0 or j>=n: return if grid[i][j]=='1': grid[i][j]='0' dz = zip([1,0,-1,0],[0,1,0,-1]) for px,py in dz: self.dfs(grid,i+px,j+py,m,n)