Skip to content

Commit a08ff79

Browse files
committed
number-of-islands sol (py)
1 parent 880bf05 commit a08ff79

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

number-of-islands/hi-rachel.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
"""
2+
https://leetcode.com/problems/number-of-islands/
3+
4+
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
5+
6+
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
7+
8+
9+
Example 1:
10+
Input: grid = [
11+
["1","1","1","1","0"],
12+
["1","1","0","1","0"],
13+
["1","1","0","0","0"],
14+
["0","0","0","0","0"]
15+
]
16+
Output: 1
17+
18+
Example 2:
19+
Input: grid = [
20+
["1","1","0","0","0"],
21+
["1","1","0","0","0"],
22+
["0","0","1","0","0"],
23+
["0","0","0","1","1"]
24+
]
25+
Output: 3
26+
27+
Constraints:
28+
m == grid.length
29+
n == grid[i].length
30+
1 <= m, n <= 300
31+
grid[i][j] is '0' or '1'.
32+
33+
BFS 풀이
34+
TC: O(m * n)
35+
SC: O(m * n)
36+
"""
37+
38+
from collections import deque
39+
from typing import List
40+
41+
class Solution:
42+
def numIslands(self, grid: List[List[str]]) -> int:
43+
ans = 0
44+
dx = [-1, 1, 0, 0]
45+
dy = [0, 0, -1, 1]
46+
rows = len(grid)
47+
cols = len(grid[0])
48+
49+
def bfs(x, y):
50+
queue = deque()
51+
queue.append((x, y))
52+
grid[x][y] = 2
53+
54+
while queue:
55+
x, y = queue.popleft()
56+
for i in range(4):
57+
nx = x + dx[i]
58+
ny = y + dy[i]
59+
if 0 <= nx < rows and 0 <= ny < cols:
60+
if grid[nx][ny] == "1":
61+
grid[nx][ny] = "2"
62+
queue.append((nx, ny))
63+
64+
return True
65+
66+
for i in range(rows):
67+
for j in range(cols):
68+
if grid[i][j] == "1":
69+
if bfs(i, j):
70+
ans += 1
71+
72+
return ans

0 commit comments

Comments
 (0)