LeetCode200. Number of Islands (思路及python解法)

173 篇文章 0 订阅

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

感觉图形有点像扫雷哈哈。

这道题是我在BFS分类里找到的,不过BFS目前的方法会超时,等待以后做DFS时候再更新DFS算法。

BFS算法的思想就是建立一个deque()(双边队列),每次遇到第一个"1"以后,把它的(r,c)加入的队列。

把队列最左面的出列,先把他修改为"0",然后再去找他的上下左右,如果有"1",就属于同一个island,也加入到队列中,这样重复操作即可。

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if len(grid)==0: return 0
        row, col = len(grid), len(grid[0])

        count = 0
        queue = collections.deque()
        steps = [[-1,0],[1,0],[0,-1],[0,1]]
        
        for i in range(row):
            for j in range(col):
                if grid[i][j]=='1' : 
                    count+=1
                    queue.append([i,j])
                    while queue:
                        x,y = queue.popleft()
                        grid[x][y] = '0'
                        for step in steps:
                            if 0<=x+step[0]<row and 0<=y+step[1]<col and grid[x+step[0]][y+step[1]] == '1':
                                queue.append([x+step[0] ,y+step[1]])
        return count  
        

等做到DFS来填坑

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值