Number of island
Medium; BFS;
Last updated
Medium; BFS;
Last updated
[[1,1,0,0,0],[0,1,0,1,1],[0,0,0,1,1],[0,0,0,0,0],[0,0,1,1,1]]301矩阵范围<=200*200class Solution:
def solve(self , grid ):
# write code here
# 1. input: 2D char array, output: number of island
# 2. BFS
# iterate every node in matrix,
# start from current node do BFS using a queue
# when queue is not empty
# if node is 1 then mark the visited node as -1 until all reachable
# node is found
# then # of island += 1
#
# test case:
#
#
#
if not grid or not grid[0]:
return 0
cnt = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
area = 0
queue = [(i,j)]
while queue:
r,c = queue.pop(0)
if r>=0 and r <len(grid) and c>=0 and c < len(grid[0]) and grid[r][c] == '1':
grid[r][c] = '-1'
queue.extend([(r-1, c), (r, c-1), (r+1, c), (r, c+1)])
area += 1
if area >0:
cnt += 1
return cnt