题解 | #岛屿数量#
岛屿数量
https://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 判断岛屿数量 # @param grid char字符型二维数组 # @return int整型 # class Solution: def solve(self, grid: List[List[str]]) -> int: # write code here nr = len(grid) if nr == 0: return 0 nc = len(grid[0]) def dfs(r: int, c: int) -> None: grid[r][c] = 0 for x, y in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]: if 0 <= x < nr and 0 <= y < nc and grid[x][y] == "1": dfs(x, y) num_islands = 0 for r in range(nr): for c in range(nc): if grid[r][c] == "1": num_islands += 1 dfs(r, c) return num_islands