Leetcode-200. Number of Islands 岛屿数量 (矩阵DFS)

题目

给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。 岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。 此外,你可以假设该网格的四条边均被水包围。 链接:https://leetcode.com/problems/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:

11000 11000 00100 00011

Output: 3

思路及代码

DFS

    遍历每一个点, 找到1后+1岛屿,在每一个点基础上进行DFS,找到1后将原矩阵置为0,直到4个方向都遇到0,则表示找完一个岛屿的所有点 Tips:if语句里写太多条件会减慢速度
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:

        def dfs(row, col):
            if grid[row][col] == 0:
                return
            grid[row][col] = 0
            if col != n - 1:
                dfs(row, col+1)
            if col != 0:
                dfs(row, col-1)
            if row != 0:
                dfs(row-1, col)
            if row != m-1:
                dfs(row+1, col)
            
        if not grid:
            return 0
        m = len(grid)
        n = len(grid[0])
        ans = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1:
                    ans += 1
                    dfs(i, j)
        return ans

复杂度

T = O ( m n ) O(mn) O(mn) S = O ( m n ) O(mn) O(mn)

经验分享 程序员 微信小程序 职场和发展