Leetcode 200. Number of Islands

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)
View Python Code

 

转载于:https://www.cnblogs.com/pegasus923/p/11271355.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值