forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path200-Number-of-Islands.py
More file actions
28 lines (24 loc) · 861 Bytes
/
200-Number-of-Islands.py
File metadata and controls
28 lines (24 loc) · 861 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid or not grid[0]:
return 0
islands = 0
q = collections.deque()
visit = set()
rows, cols = len(grid), len(grid[0])
def dfs(r, c):
if (r not in range(rows) or
c not in range(cols) or
grid[r][c] == "0" or
(r, c) in visit):
return
visit.add((r, c))
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
for dr, dc in directions:
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:
islands += 1
dfs(r, c)
return islands