Number of Islands
Fri Mar 15 2024 15:41:54 GMT+0000 (Coordinated Universal Time)
Saved by
@playadust
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
rows, cols = len(grid), len(grid[0])
visit = set()
count = 0
def dfs(r, c):
if r in range(rows) and c in range(cols) and (r,c) not in visit and grid[r][c] == "1":
visit.add((r,c))
for dr, dc in [[0, 1], [1, 0], [-1, 0], [0, -1]]:
dfs(r+dr, c+dc)
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1" and (r,c) not in visit:
count += 1
dfs(r,c)
return count
content_copyCOPY
https://leetcode.com/problems/number-of-islands/
Comments