LeetCode_Number of Islands

Number of Islands

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. DFS遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
def dfs(self, i, j):
if 0 <= i < self.m and 0 <= j < self.n and self.grid[i][j] == '1':
self.grid[i][j] = '0'
self.dfs(i+1, j)
self.dfs(i-1, j)
self.dfs(i, j+1)
self.dfs(i, j-1)

def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0

self.m, self.n = len(grid), len(grid[0])
self.grid = grid

count = 0
for i in range(self.m):
for j in range(self.n):
if self.grid[i][j] == '1':
self.dfs(i, j)
count += 1
return count