返回
如何解决岛屿计数问题?
前端
2023-10-29 06:02:03
概述
岛屿计数问题是一个经典的图论问题。给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
解决方案
解决岛屿计数问题的最直接方法是使用深度优先搜索或广度优先搜索算法。深度优先搜索算法从网格的一个单元格开始,并沿着陆地单元格的路径搜索,直到遇到水或网格的边界。广度优先搜索算法从网格的一个单元格开始,并搜索所有相邻的陆地单元格,然后搜索这些单元格的相邻单元格,依此类推。两种算法都能够找到所有的岛屿,但深度优先搜索算法通常比广度优先搜索算法更有效。
实现
以下是如何使用深度优先搜索算法解决岛屿计数问题的Python代码示例:
def count_islands(grid):
"""
Counts the number of islands in a grid.
Args:
grid: A 2D grid of '1's (land) and '0's (water).
Returns:
The number of islands in the grid.
"""
# Initialize the count of islands to 0.
num_islands = 0
# Iterate over each cell in the grid.
for i in range(len(grid)):
for j in range(len(grid[0])):
# If the current cell is land and has not been visited yet,
# then it is part of an island.
if grid[i][j] == '1' and not visited[i][j]:
# Increment the count of islands.
num_islands += 1
# Perform a depth-first search starting from the current cell.
dfs(grid, i, j)
# Return the count of islands.
return num_islands
def dfs(grid, i, j):
"""
Performs a depth-first search starting from the given cell.
Args:
grid: A 2D grid of '1's (land) and '0's (water).
i: The row index of the current cell.
j: The column index of the current cell.
"""
# Mark the current cell as visited.
visited[i][j] = True
# Check if the current cell has any unvisited neighbors.
if i > 0 and not visited[i - 1][j]:
dfs(grid, i - 1, j)
if j > 0 and not visited[i][j - 1]:
dfs(grid, i, j - 1)
if i < len(grid) - 1 and not visited[i + 1][j]:
dfs(grid, i + 1, j)
if j < len(grid[0]) - 1 and not visited[i][j + 1]:
dfs(grid, i, j + 1)
比较
深度优先搜索和广度优先搜索算法都能够解决岛屿计数问题,但深度优先搜索算法通常比广度优先搜索算法更有效。这是因为深度优先搜索算法只探索一条路径,而广度优先搜索算法需要探索所有的路径。
结论
岛屿计数问题是一个经典的图论问题,可以用深度优先搜索或广度优先搜索算法来解决。深度优先搜索算法通常比广度优先搜索算法更有效,但广度优先搜索算法可以更容易地找到所有的岛屿。