leetcode200 岛屿数量

链接

https://leetcode.cn/problems/number-of-islands/description/

思路

跟岛屿周长差不多...但我觉得这个比岛屿周长还简单。不知道为什么这个算中等题目,岛屿周长算简单题目

代码

class Solution:
    def numIslands(self, grid) -> int:
        if not grid or not grid[0]:
            return 0
        height, width = len(grid), len(grid[0])
        visited = [[False for i in range(width)] for i in range(height)]
        res = 0
        direct_x = [0, 1, 0, -1]
        direct_y = [1, 0, -1, 0]

        def dfs(i, j, visited):
            if visited[i][j] or grid[i][j] == '0':
                return
            visited[i][j] = True
            for k in range(4):
                new_x, new_y = i + direct_x[k], j + direct_y[k]
                if 0 <= new_x < height and 0 <= new_y < width and not visited[new_x][new_y] and grid[new_x][new_y] == '1':
                    dfs(new_x, new_y, visited)
        for i in range(height):
            for j in range(width):
                if not visited[i][j] and grid[i][j] == '1':
                    res += 1
                    dfs(i, j, visited)
        return res

 

posted @ 2023-10-17 10:05  BJFU-VTH  阅读(4)  评论(0编辑  收藏  举报