leetcode-200-Number-of-Islands

描述


Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return 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:

1
2
3
4
5
6
7
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1

Example 2:

1
2
3
4
5
6
7
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'.

分析


深度优先遍历算法。

解决方案1(python)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def dfs(self, grid, row, col):
grid[row][col] = 0
rowLen, colLen = len(grid), len(grid[0])
for x, y in [(row-1, col), (row+1, col), (row, col+1), (row, col-1)]:
if 0 <= x < rowLen and 0 <= y < colLen and grid[x][y] == "1":
self.dfs(grid, x, y)

def numIslands(self, grid: List[List[str]]) -> int:
rowLen = len(grid)
if rowLen == 0:
return 0
colLen = len(grid[0])
result = 0

for row in range(rowLen):
for col in range(colLen):
if grid[row][col] == "1":
result += 1
self.dfs(grid, row, col)
return result

解决方案2(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
func numIslands(grid [][]byte) int {
if len(grid) == 0 {
return 0
}
result := 0
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[0]); j++ {
if grid[i][j] == '1' {
spread(grid, i, j)
result++
}
}
}
return result
}

func spread(grid [][]byte, i, j int) {
if i < 0 || j < 0 || i >= len(grid) || j >= len(grid[0]) {
return
}
if grid[i][j] == '1' {
grid[i][j] = '0'
spread(grid, i-1, j)
spread(grid, i, j-1)
spread(grid, i+1, j)
spread(grid, i, j+1)
}
}

相关问题


题目来源