Skip to content

Commit 462899e

Browse files
committed
number of islands solution
1 parent 5b0fcd3 commit 462899e

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

number-of-islands/jungsiroo.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Solution:
2+
def numIslands(self, grid: List[List[str]]) -> int:
3+
# TC : O(n*m)
4+
# SC : O(n*m)
5+
6+
m, n = len(grid), len(grid[0])
7+
dx = [-1,1,0,0]
8+
dy = [0,0,-1,1]
9+
10+
def in_range(r, c):
11+
if r<0 or c<0 or r>=m or c>=n:
12+
return False
13+
return True
14+
15+
# DFS Way
16+
17+
def dfs(r, c):
18+
grid[r][c] = 'x'
19+
20+
for i in range(4):
21+
nr, nc = r+dx[i], c+dy[i]
22+
if not in_range(nr, nc) or grid[nr][nc] != '1':
23+
continue
24+
dfs(nr, nc)
25+
26+
# BFS Way
27+
from collections import deque
28+
def bfs(r, c):
29+
grid[r][c] = 'x'
30+
queue = deque()
31+
queue.append([r, c])
32+
33+
while queue:
34+
cr, cc = queue.popleft()
35+
for i in range(4):
36+
nr, nc = cr+dx[i], cc+dy[i]
37+
38+
if not in_range(nr, nc) or grid[nr][nc] != '1':
39+
continue
40+
grid[nr][nc] = 'x'
41+
queue.append([nr, nc])
42+
43+
ret = 0
44+
for i in range(m):
45+
for j in range(n):
46+
if grid[i][j] == '1':
47+
bfs(i, j)
48+
ret += 1
49+
return ret
50+

0 commit comments

Comments
 (0)