-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.py
42 lines (35 loc) · 1.18 KB
/
solution.py
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from typing import List
import collections
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
visit = set()
islands = 0
def bfs(r, c):
q = collections.deque()
visit.add((r, c))
q.append((r, c))
while q:
row, col = q.pop()
directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
for dr, dc in directions:
r, c = row + dr, col + dc
if (r in range(rows) and c in range(cols) and grid[r][c] == "1" and (r, c) not in visit):
q.append((r, c))
visit.add((r, c))
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1" and (r, c) not in visit:
bfs(r, c)
islands += 1
return islands
if __name__ == '__main__':
grid = [
["1", "1", "1", "1", "0"],
["1", "1", "0", "1", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "0", "0", "0"]
]
print(Solution().numIslands(grid))