目录

  1. 寻路算法概述
  2. 经典寻路算法
  3. 寻路算法的应用
  4. 参考资料

1. 寻路算法概述

寻路算法主要用于在图或网格中找到 起点到终点的最优路径,广泛应用于:

  • 地图导航(如 Google Maps)
  • 游戏 AI(如 NPC 移动)
  • 机器人路径规划
  • 网络路由优化

寻路问题一般分为 单源最短路径全源最短路径

  • 单源最短路径(从单个起点到所有可达点的最短路径):BFS、Dijkstra、Bellman-Ford、A*
  • 全源最短路径(求解图中所有点对间的最短路径):Floyd-Warshall、Johnson

2. 经典寻路算法

2.1 广度优先搜索(BFS)

适用于 无权图,寻找最短路径。

Python 实现

from collections import deque

def bfs(grid, start, goal):
    rows, cols = len(grid), len(grid[0])
    queue = deque([(start, [start])])  # (当前节点, 当前路径)
    visited = set()

    while queue:
        (x, y), path = queue.popleft()
        if (x, y) == goal:
            return path

        for dx, dy in [(-1,0), (1,0), (0,-1), (0,1)]:
            nx, ny = x + dx, y + dy
            if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 0 and (nx, ny) not in visited:
                visited.add((nx, ny))
                queue.append(((nx, ny), path + [(nx, ny)]))

    return None  # 无路径

grid = [
    [0, 1, 0, 0, 0],
    [0, 1, 0, 1, 0],
    [0, 0, 0, 1, 0],
    [1, 1, 0, 0, 0]
]
print(bfs(grid, (0, 0), (3, 4)))

时间复杂度:O(V+E)O(V + E)
空间复杂度:O(V)O(V)


2.2 深度优先搜索(DFS)

DFS 主要用于 路径探索,但不保证最短路径。

Python 实现

def dfs(grid, start, goal, path=[], visited=set()):
    x, y = start
    if start == goal:
        return path + [start]

    visited.add(start)
    for dx, dy in [(-1,0), (1,0), (0,-1), (0,1)]:
        nx, ny = x + dx, y + dy
        if (0 <= nx < len(grid) and 0 <= ny < len(grid[0]) and 
            grid[nx][ny] == 0 and (nx, ny) not in visited):
            result = dfs(grid, (nx, ny), goal, path + [start], visited)
            if result:
                return result

    return None

时间复杂度:O(V+E)O(V + E)
空间复杂度:O(V)O(V)


2.3 Dijkstra 算法

用于 加权图,适用于 无负权边 的最短路径问题。

Python 实现

import heapq

def dijkstra(graph, start):
    pq = [(0, start)]  # (当前距离, 当前节点)
    distances = {node: float('inf') for node in graph}
    distances[start] = 0

    while pq:
        curr_dist, node = heapq.heappop(pq)

        if curr_dist > distances[node]:
            continue

        for neighbor, weight in graph[node]:
            distance = curr_dist + weight
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(pq, (distance, neighbor))

    return distances

时间复杂度:O((V+E)log⁡V)O((V+E) \log V)


2.4 A* 算法

用于 启发式搜索,适用于 网格路径规划

Python 实现

def heuristic(a, b):
    return abs(a[0] - b[0]) + abs(a[1] - b[1])

def a_star(grid, start, goal):
    open_set = [(0, start)]
    came_from = {}
    g_score = {start: 0}
    f_score = {start: heuristic(start, goal)}

    while open_set:
        _, current = heapq.heappop(open_set)

        if current == goal:
            path = []
            while current in came_from:
                path.append(current)
                current = came_from[current]
            return path[::-1]

        for dx, dy in [(-1,0), (1,0), (0,-1), (0,1)]:
            neighbor = (current[0] + dx, current[1] + dy)
            if 0 <= neighbor[0] < len(grid) and 0 <= neighbor[1] < len(grid[0]) and grid[neighbor[0]][neighbor[1]] == 0:
                tentative_g_score = g_score[current] + 1
                if tentative_g_score < g_score.get(neighbor, float('inf')):
                    came_from[neighbor] = current
                    g_score[neighbor] = tentative_g_score
                    f_score[neighbor] = tentative_g_score + heuristic(neighbor, goal)
                    heapq.heappush(open_set, (f_score[neighbor], neighbor))

时间复杂度:O((V+E)log⁡V)O((V+E) \log V)


2.5 Floyd-Warshall 算法

全源最短路径算法,用于加权图,支持 负权边(但不能有负环)。

Python 实现

def floyd_warshall(graph):
    V = len(graph)
    dist = list(map(lambda i: list(map(lambda j: j, i)), graph))

    for k in range(V):
        for i in range(V):
            for j in range(V):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

    return dist

时间复杂度:O(V3)O(V^3)


4. 参考资料

出站链接

站内链接