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.
- 宽度优先搜索四个方向遍历整个图
- 访问过的节点标记为0
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
count = 0
if not grid or not grid[0]:
return count
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
self.bfs(grid, i, j)
count += 1
return count
def bfs(self, grid, i, j):
queue = collections.deque([(i,j)])
grid[i][j] = '0'
while queue:
x, y = queue.popleft()
for delta_x, delta_y in [(1,0), (0,1), (-1,0), (0,-1)]:
new_x, new_y = x + delta_x, y + delta_y
if not self.valid(grid, new_x, new_y):
continue
queue.append((new_x, new_y))
grid[new_x][new_y] = '0'
def valid(self, grid, i, j):
m, n = len(grid), len(grid[0])
return 0 <= i < m and 0 <= j < n and grid[i][j] == '1'