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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?