Leetcode 200. Number of Islands

https://leetcode.com/problems/number-of-islands/css

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.ide

Example 1:spa

Input:
11110
11010
11000
00000

Output: 1

Example 2:code

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)
View Python Code
相關文章
相關標籤/搜索