-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberofIsland_Day71.py
More file actions
89 lines (71 loc) · 2.23 KB
/
Copy pathNumberofIsland_Day71.py
File metadata and controls
89 lines (71 loc) · 2.23 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#Brute Approach
from typing import List
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
visited = [[False] * cols for _ in range(rows)]
def dfs(r, c):
if (r < 0 or c < 0 or r >= rows or c >= cols or
grid[r][c] == "0" or visited[r][c]):
return
visited[r][c] = True
dfs(r+1, c)
dfs(r-1, c)
dfs(r, c+1)
dfs(r, c-1)
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1" and not visited[r][c]:
dfs(r, c)
count += 1
return count
#Better Approach
from typing import List
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
def dfs(r, c):
if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] == "0":
return
grid[r][c] = "0"
dfs(r+1, c)
dfs(r-1, c)
dfs(r, c+1)
dfs(r, c-1)
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1":
dfs(r, c)
count += 1
return count
#Optimal Approach
from typing import List
from collections import deque
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
def bfs(r, c):
q = deque([(r, c)])
grid[r][c] = "0"
while q:
x, y = q.popleft()
for dx, dy in [(1,0), (-1,0), (0,1), (0,-1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == "1":
grid[nx][ny] = "0"
q.append((nx, ny))
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1":
bfs(r, c)
count += 1
return count