200. Number of Islands
Medium
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
笔记:
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
row_len = len(grid)
col_len = len(grid[0])
rlt = 0
def dfs(x, y):
if x < 0 or x >= row_len or y < 0 or y >= col_len:
return
if grid[x][y] == '0':
return
grid[x][y] = '0'
dfs(x, y -1)
dfs(x - 1, y)
dfs(x, y + 1)
dfs(x + 1, y)
for x in range(row_len):
for y in range(col_len):
if grid[x][y] == '1':
rlt += 1
dfs(x, y)
return rlt