Number of Big Islands
franklinqin0 BFS
# Input & Output
@param grid: a 2d boolean array
@param k: an integer
@return: the number of Islands
1
2
3
2
3
# Solution
Let be the number of rows and be the number of columns.
# BFS
Complexity
time:
space:
DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def numsofIsland(self, grid, k):
n, m = len(grid), len(grid[0])
def bfs(i, j):
queue = [(i, j)]
size = 0
while queue:
x, y = queue.pop(0)
for dx, dy in DIRECTIONS:
nx, ny = x+dx, y+dy
if 0 <= nx < n and 0 <= ny < m and grid[nx][ny]:
size += 1
grid[nx][ny] = False
queue.append((nx, ny))
return size
res = 0
for i in range(n):
for j in range(m):
if grid[i][j] and bfs(i, j) >= k:
res += 1
return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25