forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0200-number-of-islands.py
66 lines (51 loc) · 1.82 KB
/
0200-number-of-islands.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
classSolution:
defnumIslands(self, grid: List[List[str]]) ->int:
ifnotgridornotgrid[0]:
return0
islands=0
visit=set()
rows, cols=len(grid), len(grid[0])
defdfs(r, c):
if (
rnotinrange(rows)
orcnotinrange(cols)
orgrid[r][c] =="0"
or (r, c) invisit
):
return
visit.add((r, c))
directions= [[0, 1], [0, -1], [1, 0], [-1, 0]]
fordr, dcindirections:
dfs(r+dr, c+dc)
forrinrange(rows):
forcinrange(cols):
ifgrid[r][c] =="1"and (r, c) notinvisit:
islands+=1
dfs(r, c)
returnislands
# BFS Version From Video
classSolutionBFS:
defnumIslands(self, grid: List[List[str]]) ->int:
ifnotgrid:
return0
rows, cols=len(grid), len(grid[0])
visited=set()
islands=0
defbfs(r,c):
q=deque()
visited.add((r,c))
q.append((r,c))
whileq:
row,col=q.popleft()
directions= [[1,0],[-1,0],[0,1],[0,-1]]
fordr,dcindirections:
r,c=row+dr, col+dc
if (r) inrange(rows) and (c) inrange(cols) andgrid[r][c] =='1'and (r ,c) notinvisited:
q.append((r , c ))
visited.add((r, c ))
forrinrange(rows):
forcinrange(cols):
ifgrid[r][c] =="1"and (r,c) notinvisited:
bfs(r,c)
islands+=1
returnislands