Skip to content

Commit 85ff3e3

Browse files
committed
Time: 236 ms (81.16%), Space: 20.1 MB (68.88%) - LeetHub
1 parent 245f8aa commit 85ff3e3

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)