题目:
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:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
题解:初始版本:代码长但是运行速度快
def dfs(r,c):
grid[r][c]=‘0’
for x,y in ((r-1,c),(r+1,c),(r,c-1),(r,c+1)):
if 0<=x<R and 0<=y<C and grid[x][y]‘1’:
dfs(x,y)
if not grid:
return 0
R,C,count=len(grid),len(grid[0]),0
for i in range®:
for j in range©:
if grid[i][j]‘1’:
count+=1
dfs(i,j)
return count
更简短的版本,但是执行起来速度慢:
def numIslands(self, grid):
def sink(i, j):
if 0 <= i < len(grid) and 0 <= j < len(grid[i]) and grid[i][j] == ‘1’:
grid[i][j] = ‘0’
map(sink, (i+1, i-1, i, i), (j, j, j+1, j-1))
return 1
return 0
return sum(sink(i, j) for i in range(len(grid)) for j in range(len(grid[i])))