[LeetCode] 200. Number of Islands_ Medium tag: BFS

时间:2024-03-25 15:37:08

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. 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.

Example 1:

Input:
11110
11010
11000
00000 Output: 1

Example 2:

Input:
11000
11000
00100
00011 Output: 3 这个题目也是经典的BFS, 思路就是将2D array扫一遍, 然后每次如果扫到的元素是'1' and not in visited, ans += 1, 并且建一个queue, 将所有跟它相邻的4个元素如果是'1' 并且没有visited过的,
append进入queue, mark 为visited, recursively直到把所有4个方向的'1' 的元素都mark为visited, 然后一直把整个array扫完, 然后return ans. 1. Constraints 1) array can be empty or col == 0 , return 0
2) the element in array will only be '1' or '0' 2. Ideas BFS: T: O(m*n) S: O(m*n) 3. Code
 class Solution:
def numIslands(self, grid):
ans,visited = 0, set()
if not grid or len(grid[0]) == 0: return ans
lr, lc = len(grid), len(grid[0])
for i in range(lr):
for j in range(lc):
if grid[i][j] == '' and (i,j) not in visited:
ans += 1
visited.add((i,j))
queue, dirs = collections.deque([(i,j)]), [(0,1), (0,-1), (-1,0), (1,0)]
while queue:
r, c = queue.popleft()
for d1, d2 in dirs:
nr, nc = r + d1, c + d2
if 0<= nr < lr and 0<= nc < lc and grid[nr][nc] == '' and (nr, nc) not in visited:
queue.append((nr, nc))
visited.add((nr,nc))
return ans

4. test cases

1) [], [[]]

2) [[1]]

3)

Input:
11110
11010
11000
00000 Output: 1

4)

Input:
11000
11000
00100
00011 Output: 3