Skip to content

Latest commit

 

History

History
76 lines (57 loc) · 2.47 KB

File metadata and controls

76 lines (57 loc) · 2.47 KB

https://leetcode-cn.com/problems/number-of-islands/solution/200dao-yu-shu-liang-ju-zhen-sou-suo-top3-ww71/

难度:中等

题目

给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。

岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

此外,你可以假设该网格的四条边均被水包围。

示例

示例 1:
输入:grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
输出:1

示例 2:
输入:grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
输出:3

分析

推荐下矩阵搜索的经典三连发:

针对这道题,我们只需要对矩阵进行依次遍历,如果当前grid[x][y] == "1",则启动DFS模式。 找到与之相连的所有1,将其置为0。搜索结束后,我们找到了一个岛屿,岛屿数量+=1。 如此循环,最终返回岛屿数量即可。

解题

class Solution:
    def numIslands(self, grid):
        row, col, ret = len(grid), len(grid[0]), 0

        def dfs(x, y):
            grid[x][y] = '0'
            for c in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
                nx, ny = x + c[0], y + c[1]
                if 0 <= nx < row and 0 <= ny < col and grid[nx][ny] == '1':
                    dfs(nx, ny)

        for i in range(row):
            for j in range(col):
                if grid[i][j] == '1':
                    dfs(i, j)
                    ret += 1
        return ret

欢迎关注我的公众号: 清风Python,带你每日学习Python算法刷题的同时,了解更多python小知识。

有喜欢力扣刷题的小伙伴可以加我微信(King_Uranus)互相鼓励,共同进步,一起玩转超级码力!

我的个人博客:https://qingfengpython.cn

力扣解题合集:https://github.com/BreezePython/AlgorithmMarkdown