https://leetcode.com/problems/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
- DFS / BFS经典题目。从一个点开始扩展,把所有连通的点都标记为已访问,这些点都属于一个岛。搜索题目就是要确定策略套模版。
- 注意时间空间复杂度都是O(m * n)。最坏情况下每个点都访问到。
1 class Solution: 2 def numIslands(self, grid: List[List[str]]) -> int: 3 if not grid: 4 return 0 5 6 self.x = len(grid) 7 self.y = len(grid[0]) 8 count = 0 9 10 for i in range(self.x): 11 for j in range(self.y): 12 if grid[i][j] == '1': 13 self.DFS(grid, i, j) 14 count += 1 15 16 return count 17 18 def DFS(self, g: List[List[str]], x: int, y: int): 19 if x < 0 or x >= self.x or y < 0 or y >= self.y or g[x][y] == '0': 20 return 21 22 g[x][y] = '0' 23 24 self.DFS(g, x - 1, y) 25 self.DFS(g, x + 1, y) 26 self.DFS(g, x, y - 1) 27 self.DFS(g, x, y + 1)