We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 245f8aa commit 85ff3e3Copy full SHA for 85ff3e3
0200-number-of-islands/0200-number-of-islands.py
@@ -0,0 +1,34 @@
1
+from collections import deque
2
+
3
+class Solution:
4
+ def numIslands(self, grid: List[List[str]]) -> int:
5
+ n = len(grid)
6
+ m = len(grid[0])
7
+ visited = [[False] * m for _ in range(n)]
8
+ cnt = 0
9
10
+ def bfs(a, b):
11
+ q = deque([(a, b)])
12
+ dx = [1, -1, 0, 0]
13
+ dy = [0, 0, 1, -1]
14
15
+ while q:
16
+ x, y = q.popleft()
17
18
+ for i in range(4):
19
+ nx = x + dx[i]
20
+ ny = y + dy[i]
21
22
+ if 0 <= nx < n and 0 <= ny < m and not visited[nx][ny] and grid[nx][ny] == '1':
23
+ q.append((nx, ny))
24
+ visited[nx][ny] = True
25
26
27
28
+ for i in range(n):
29
+ for j in range(m):
30
+ if grid[i][j] == '1' and not visited[i][j]:
31
+ bfs(i, j)
32
+ cnt += 1
33
34
+ return cnt
0 commit comments