Skip to content

Commit 8818b5f

Browse files
committed
Number Of Islands Solution
1 parent 64467df commit 8818b5f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

number-of-islands/naringst.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
from collections import deque
2+
3+
# Runtime: 241ms, Memory: 18.94MB
4+
# Time complexity: O(len(n*m))
5+
# Space complexity: O(len(n*m))
6+
7+
8+
class Solution:
9+
def bfs(self, a,b, grid, visited) :
10+
n = len(grid)
11+
m = len(grid[0])
12+
13+
dx = [0, 0, 1, -1]
14+
dy = [1, -1 ,0 ,0]
15+
q = deque()
16+
q.append([a,b])
17+
visited[a][b] = True
18+
19+
while q :
20+
x,y = q.popleft()
21+
22+
for i in range(4) :
23+
nx = x + dx[i]
24+
ny = y + dy[i]
25+
26+
if (0 <= nx < n and 0 <= ny < m and not visited[nx][ny] and grid[nx][ny] == '1'):
27+
visited[nx][ny] = True
28+
q.append([nx,ny])
29+
30+
31+
32+
def numIslands(self, grid: List[List[str]]) -> int:
33+
n = len(grid)
34+
m = len(grid[0])
35+
visited = [[False] * m for _ in range(n)]
36+
answer = 0
37+
38+
for i in range(n) :
39+
for j in range(m) :
40+
if grid[i][j] == '1' and not visited[i][j] :
41+
self.bfs(i,j,grid,visited)
42+
answer += 1
43+
44+
return answer

0 commit comments

Comments
 (0)