LeetCode 200. Number of Islands (岛屿数量)

原题

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

Reference Answer

思路分析

我们遍历矩阵的每一个点,对每个点都尝试进行一次深度优先搜索,如果搜索到1,就继续向它的四周搜索。同时我们每找到一个1,就将其标为0,这样就能把整个岛屿变成0。我们只要记录对矩阵遍历时能进入多少次搜索,就代表有多少个岛屿。

这道题开始想成用动态规划求解,设置了mark_grid,进行求解遍历事实上,动态规划很难进行求解,如开始对第一行及第一列进行遍历判别,然后会存在以下形式不满足:

Input:
111
010
111
Output: 1(却被程序判别为2,因为把左下角当做一个独立岛屿看待了)

而当先对左上角、左下角与右上角进行设置后,依旧不满足,因为存在

Input:
11
Output: 1(却被程序判别为2,因为把右上角当做一个独立岛屿看待了)

最后,放弃动态规划,改用DFS。

Code

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        
        if not grid:
            return 0
        rows = len(grid)
        cols = len(grid[0])

        res = 0
        
        for row in range(rows):
            for col in range(cols):
                if grid[row][col] == '1':
                    self.explore(grid, row, col)
                    res += 1
                    
        return res
        
    def explore(self, grid, row, col):
        grid[row][col] = '0'
        if row > 0 and grid[row-1][col] == '1':
            self.explore(grid, row-1, col)
        if col > 0 and grid[row][col-1] == '1':
            self.explore(grid, row, col-1)
        if row < len(grid)-1 and grid[row+1][col] == '1':
            self.explore(grid, row+1, col)
        if col < len(grid[0])-1 and grid[row][col+1] == '1':
            self.explore(grid, row, col+1)
             

Note:

  • 动态规划与DFS到底用哪个要仔细琢磨清楚!

参考资料

[1] https://segmentfault.com/a/1190000003753307

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值