Graph—最短路算法
(old_version)
Dijkstra最短路径算法(C++实现)
Dijkstra算法是一种用于在加权图中找到单源最短路径的经典算:
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
// 使用邻接表表示图
typedef pair<int, int> pii; // (顶点, 权重)
vector<int> dijkstra(const vector<vector<pii>>& graph, int start)
{
int n = graph.size();
vector<int> dist(n, INT_MAX); // 存储起点到各点的最短距离
vector<bool> visited(n, false); // 标记顶点是否已访问
// 优先队列,存储(距离, 顶点),按距离从小到大排序
priority_queue<pii, vector<pii>, greater<pii>> pq;
dist[start] = 0;
pq.push({0, start});
while (!pq.empty())
{
int u = pq.top().second;
pq.pop();
if (visited[u]) continue;
visited[u] = true;
// 遍历u的所有邻接顶点
for (auto& edge : graph[u])
{
int v = edge.first;
int weight = edge.second;
// 松弛操作
if (dist[v] > dist[u] + weight)
{
dist[v] = dist[u] + weight;
pq.push({dist[v], v});
}
}
}
return dist;
}
int main()
{
// 示例图
int n = 5; // 顶点数
vector<vector<pii>> graph(n);
// 添加边 (无向图)
graph[0].emplace_back(1, 4);
graph[0].emplace_back(2, 1);
graph[1].emplace_back(0, 4);
graph[1].emplace_back(2, 2);
graph[1].emplace_back(3, 5);
graph[2].emplace_back(0, 1);
graph[2].emplace_back(1, 2);
graph[2].emplace_back(3, 1);
graph[3].emplace_back(1, 5);
graph[3].emplace_back(2, 1);
graph[3].emplace_back(4, 3);
graph[4].emplace_back(3, 3);
int start = 0; // 起点
vector<int> dist = dijkstra(graph, start);
cout << "从顶点 " << start << " 到各顶点的最短距离:\n";
for (int i = 0; i < n; ++i)
{
if (dist[i] == INT_MAX)
cout << "顶点 " << i << ": 不可达\n";
else
cout << "顶点 " << i << ": " << dist[i] << "\n";
}
return 0;
}
算法说明
- 初始化:
- 设置所有顶点的初始距离为无穷大(
INT_MAX) - 起点的距离为
0 - 使用优先队列(最小堆)存储待处理的顶点
- 主循环:
- 每次从队列中取出距离最小的顶点
u - 标记
u 为已访问 - 对
u 的所有邻接顶点v 进行松弛操作:如果通过u 到达v 的路径比当前已知路径更短,则更新v的距离
- 复杂度:
- 时间复杂度:
O((V+E)\log V) ,其中V 是顶点数,E 是边数 - 空间复杂度:
O(V)
注意事项
- 该实现适用于无负权边的图
- 对于稠密图,可以考虑不使用优先队列,而是每次线性搜索最小距离顶点(时间复杂度
O(V^2) ) - 如果需要记录路径,可以添加一个
parent数组来记录每个顶点的前驱节点
可以根据具体需求调整图的表示方式或输出格式。
Floyd最短路径算法(C++实现)
Floyd算法(又称Floyd-Warshall算法)是一种用于寻找加权图中所有顶点对之间最短路径的动态规划算法。它可以处理有向图或无向图,边的权重可以为正也可以为负(但不能有负权回路)。
算法实现
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
const int INF = INT_MAX / 2; // 避免整数溢出
void floyd(vector<vector<int>>& dist)
{
int n = dist.size();
// 三重循环实现动态规划
for (int k = 0; k < n; ++k)
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
{
// 如果通过k顶点中转的路径更短,则更新距离
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
void printSolution(const vector<vector<int>>& dist)
{
int n = dist.size();
cout << "各顶点对之间的最短距离:\n";
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
if (dist[i][j] == INF)
cout << "INF\t";
else
cout << dist[i][j] << "\t";
}
cout << endl;
}
}
int main()
{
// 示例图(邻接矩阵表示)
int n = 4; // 顶点数
vector<vector<int>> graph =
{
{0, 5, INF, 10}, // 0到其他顶点的距离
{INF, 0, 3, INF}, // 1到其他顶点的距离
{INF, INF, 0, 1}, // 2到其他顶点的距离
{INF, INF, INF, 0} // 3到其他顶点的距离
};
// 复制图,因为Floyd算法会修改原始矩阵
vector<vector<int>> dist = graph;
floyd(dist);
printSolution(dist);
return 0;
}
算法说明
- 初始化:
- 使用邻接矩阵表示图,
dist[i][j] 表示顶点i 到顶点j 的直接距离 - 对角线元素设为
0 (顶点到自身的距离为0 ) - 不直接相连的顶点距离设为
INF(无穷大)
- 动态规划核心:
- 三重循环遍历所有顶点对
(i,j) 和所有可能的中转顶点k - 状态转移方程:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) - 通过不断尝试所有可能的中转顶点
k 来更新最短距离
- 复杂度分析:
- 时间复杂度:
O(V^3) ,其中V 是顶点数 - 空间复杂度:
O(V^2) ,需要存储距离矩阵
算法特点
-
优点:
-
可以计算所有顶点对之间的最短路径
-
代码简单,易于实现
-
可以检测图中是否存在负权回路(检查对角线元素是否为负)
-
缺点:
-
时间复杂度较高,不适合大规模图
-
不能处理包含负权回路的图(但可以检测到)
扩展功能
如果需要记录具体路径,可以添加一个next矩阵:
vector<vector<int>> next(n, vector<int>(n, -1));
// 初始化next矩阵
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
if (graph[i][j] != INF && i != j)
next[i][j] = j;
// 在Floyd算法中更新next矩阵
if (dist[i][k] + dist[k][j] < dist[i][j])
{
dist[i][j] = dist[i][k] + dist[k][j];
next[i][j] = next[i][k];
}
然后可以通过next矩阵重建具体路径。
Ford最短路径算法(C++实现)
Ford算法(通常指Bellman-Ford算法)是一种用于计算单源最短路径的算法,可以处理带有负权边的图,并能检测出图中是否存在负权回路。
Bellman-Ford算法实现
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
struct Edge
{
int src, dest, weight;
};
bool bellmanFord(const vector<Edge>& edges, int V, int E, int src, vector<int>& dist)
{
// 初始化距离数组
dist.assign(V, INT_MAX);
dist[src] = 0;
// 松弛所有边 V-1 次
for (int i = 1; i <= V - 1; ++i)
{
for (int j = 0; j < E; ++j)
{
int u = edges[j].src;
int v = edges[j].dest;
int weight = edges[j].weight;
if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
// 检查是否存在负权回路
for (int i = 0; i < E; ++i)
{
int u = edges[i].src;
int v = edges[i].dest;
int weight = edges[i].weight;
if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
return false; // 存在负权回路
}
return true; // 不存在负权回路
}
void printSolution(const vector<int>& dist)
{
int V = dist.size();
cout << "顶点\t距离源点的距离\n";
for (int i = 0; i < V; ++i)
if (dist[i] == INT_MAX)
cout << i << "\tINF\n";
else
cout << i << "\t" << dist[i] << "\n";
}
int main()
{
int V = 5; // 顶点数
int E = 8; // 边数
vector<Edge> edges =
{
{0, 1, -1}, {0, 2, 4},
{1, 2, 3}, {1, 3, 2},
{1, 4, 2}, {3, 2, 5},
{3, 1, 1}, {4, 3, -3}
};
int src = 0; // 源点
vector<int> dist(V);
if (bellmanFord(edges, V, E, src, dist))
{
cout << "图中不包含负权回路\n";
printSolution(dist);
}
else
cout << "图中包含负权回路\n";
return 0;
}
算法说明
- 初始化:
- 设置源点到自身的距离为
0 - 设置其他所有顶点的距离为无穷大(
INT_MAX)
- 松弛操作:
- 对所有边进行
V-1 次松弛操作 - 每次松弛操作尝试更新通过当前边能否获得更短路径
- 负权回路检测:
- 再进行一次松弛操作
- 如果还能找到更短路径,则说明图中存在负权回路
算法特点
- 时间复杂度:
O(V*E) ,其中V 是顶点数,E 是边数 - 空间复杂度:
O(V) ,用于存储距离数组 - 优点:
- 可以处理带有负权边的图
- 能够检测负权回路
- 缺点:
- 比
Dijkstra算法慢 - 对于稠密图效率较低
扩展功能
如果需要记录路径,可以添加一个parent数组:
vector<int> parent(V, -1);
// 在松弛操作中更新parent数组
if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
{
dist[v] = dist[u] + weight;
parent[v] = u;
}
// 打印路径的函数
void printPath(const vector<int>& parent, int v)
{
if (v == -1) return;
printPath(parent, parent[v]);
cout << v << " ";
}
这个实现可以处理大多数情况下的最短路径问题,特别是当图中包含负权边时,Bellman-Ford算法是一个可靠的选择。
SPFA最短路径算法(C++实现)
SPFA(Shortest Path Faster Algorithm)是Bellman-Ford算法的队列优化版本,用于计算单源最短路径,可以处理负权边并检测负权回路。
SPFA算法实现
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
const int INF = INT_MAX;
struct Edge
{
int to;
int weight;
};
bool SPFA(const vector<vector<Edge>>& graph, int src, vector<int>& dist)
{
int V = graph.size();
dist.assign(V, INF);
vector<int> count(V, 0); // 记录顶点入队次数
vector<bool> inQueue(V, false); // 记录顶点是否在队列中
queue<int> q;
dist[src] = 0;
q.push(src);
inQueue[src] = true;
count[src]++;
while (!q.empty())
{
int u = q.front();
q.pop();
inQueue[u] = false;
// 遍历所有邻接边
for (const Edge& edge : graph[u])
{
int v = edge.to;
int weight = edge.weight;
// 松弛操作
if (dist[u] + weight < dist[v])
{
dist[v] = dist[u] + weight;
if (!inQueue[v])
{
q.push(v);
inQueue[v] = true;
count[v]++;
// 如果顶点入队次数超过V次,说明存在负权回路
if (count[v] > V)
return false;
}
}
}
}
return true;
}
void printSolution(const vector<int>& dist)
{
int V = dist.size();
cout << "顶点\t距离源点的距离\n";
for (int i = 0; i < V; ++i)
if (dist[i] == INF)
cout << i << "\tINF\n";
else
cout << i << "\t" << dist[i] << "\n";
}
int main()
{
int V = 5; // 顶点数
vector<vector<Edge>> graph(V);
// 构建图 (有向图)
graph[0].push_back({1, -1});
graph[0].push_back({2, 4});
graph[1].push_back({2, 3});
graph[1].push_back({3, 2});
graph[1].push_back({4, 2});
graph[3].push_back({2, 5});
graph[3].push_back({1, 1});
graph[4].push_back({3, -3});
int src = 0; // 源点
vector<int> dist(V);
if (SPFA(graph, V, src, dist))
{
cout << "图中不包含负权回路\n";
printSolution(dist);
}
else
cout << "图中包含负权回路\n";
return 0;
}
算法说明
- 初始化:
- 使用邻接表存储图结构
- 距离数组初始化为
INF,源点距离为0 - 使用队列优化
Bellman-Ford算法
- 核心过程:
- 从队列中取出顶点
u - 对u的所有邻接边进行松弛操作
- 如果顶点
v 的距离被更新且不在队列中,则加入队列
- 负权回路检测:
- 记录每个顶点入队次数
- 如果某个顶点入队次数超过V次,则存在负权回路
算法特点
-
时间复杂度:
-
平均情况:
O(E) ,优于Bellman-Ford的O(VE) -
最坏情况:
O(VE) ,与Bellman-Ford相同 -
空间复杂度:
O(V + E) -
优点:
-
在稀疏图上效率高
-
可以处理负权边
-
能够检测负权回路
-
缺点:
-
最坏情况下性能与
Bellman-Ford相同 -
对于精心设计的稠密图可能退化为
O(VE)
扩展功能
如果需要记录路径,可以添加parent数组:
vector<int> parent(V, -1);
// 在松弛操作中更新parent
if (dist[u] + weight < dist[v])
{
dist[v] = dist[u] + weight;
parent[v] = u;
// ...
}
// 打印路径
void printPath(const vector<int>& parent, int v)
{
if (v == -1) return;
printPath(parent, parent[v]);
cout << v << " ";
}
SPFA算法在实践中对于随机图表现优异,特别适合处理带有负权边但不含负权回路的图。
A*最短路径算法(C++实现)
A*算法是一种启发式搜索算法,常用于路径查找和图遍历。它结合了Dijkstra算法的完备性和贪心最佳优先搜索的高效性,通过启发式函数来优化搜索过程。
A*算法实现
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>
#include <unordered_map>
#include <algorithm>
using namespace std;
struct Node
{
int id;
int x, y; // 坐标用于启发式函数计算
int g; // 从起点到当前节点的实际代价
int h; // 从当前节点到终点的估计代价
int f; // g + h
Node* parent;
Node(int id, int x, int y) : id(id), x(x), y(y), g(0), h(0), f(0), parent(nullptr) {}
// 重载<运算符用于优先队列
bool operator<(const Node& other) const
{
return f > other.f; // 小顶堆
}
};
// 计算两点之间的欧几里得距离(启发式函数)
double heuristic(const Node& a, const Node& b)
{
return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2));
}
vector<Node*> aStar(vector<Node>& nodes, const vector<vector<pair<int, int>>>& graph,
Node* start, Node* end)
{
// 开放列表(优先队列)
priority_queue<Node*> openSet;
// 关闭列表
unordered_map<int, bool> closedSet;
// 节点集合
unordered_map<int, Node*> allNodes;
// 初始化所有节点
for (auto& node : nodes)
{
node.g = INT_MAX;
node.h = heuristic(node, *end);
node.f = node.g + node.h;
node.parent = nullptr;
allNodes[node.id] = &node;
}
// 设置起点
start->g = 0;
start->f = start->g + start->h;
openSet.push(start);
while (!openSet.empty())
{
Node* current = openSet.top();
openSet.pop();
// 找到终点
if (current->id == end->id)
{
// 重构路径
vector<Node*> path;
while (current != nullptr)
{
path.push_back(current);
current = current->parent;
}
reverse(path.begin(), path.end());
return path;
}
closedSet[current->id] = true;
// 遍历邻居
for (const auto& edge : graph[current->id])
{
int neighborId = edge.first;
int edgeWeight = edge.second;
if (closedSet[neighborId]) continue;
Node* neighbor = allNodes[neighborId];
int tentative_g = current->g + edgeWeight;
if (tentative_g < neighbor->g)
{
neighbor->parent = current;
neighbor->g = tentative_g;
neighbor->f = neighbor->g + neighbor->h;
// 这里简单实现,实际应该检查是否已在openSet中
openSet.push(neighbor);
}
}
}
return {}; // 没有找到路径
}
void printPath(const vector<Node*>& path)
{
if (path.empty())
{
cout << "没有找到路径" << endl;
return;
}
cout << "找到的路径: ";
for (size_t i = 0; i < path.size(); ++i)
{
cout << path[i]->id;
if (i != path.size() - 1)
cout << " -> ";
}
cout << "\n总代价: " << path.back()->g << endl;
}
int main()
{
// 创建节点 (id, x, y)
vector<Node> nodes =
{
{0, 0, 0}, // A
{1, 1, 2}, // B
{2, 3, 1}, // C
{3, 4, 3}, // D
{4, 5, 0} // E
};
// 邻接表表示的图 (to, weight)
vector<vector<pair<int, int>>> graph =
{
{{1, 3}, {2, 5}}, // A
{{0, 3}, {2, 1}, {3, 7}}, // B
{{0, 5}, {1, 1}, {3, 2}, {4, 6}}, // C
{{1, 7}, {2, 2}, {4, 3}}, // D
{{2, 6}, {3, 3}} // E
};
Node* start = &nodes[0]; // A
Node* end = &nodes[4]; // E
vector<Node*> path = aStar(nodes, graph, start, end);
printPath(path);
return 0;
}
算法说明
-
数据结构:
Node结构体存储节点信息,包括坐标、代价和父节点- 优先队列(开放列表)用于存储待探索节点
- 哈希表(关闭列表)记录已探索节点
-
核心步骤:
- 初始化所有节点的
g 、h 、f 值 - 将起点加入开放列表
- 循环从开放列表取出
f 值最小的节点 - 如果是终点则重构路径
- 否则处理所有邻居节点,更新代价和父节点
- 初始化所有节点的
-
启发式函数:
- 使用欧几里得距离估计当前节点到终点的代价
- 可根据实际问题选择曼哈顿距离等其他启发式函数
算法特点
- 时间复杂度:取决于启发式函数的质量,最好情况
O(b^d) ,最坏情况O(b^d) - 空间复杂度:
O(b^d) ,需要存储所有生成的节点 - 优点:
- 比
Dijkstra算法更快找到路径 - 可以处理带有启发式信息的图
- 能找到最优解(当启发式函数可采纳时)
- 比
- 缺点:
- 需要设计好的启发式函数
- 空间复杂度较高
扩展功能
- 不同启发式函数:
// 曼哈顿距离 int manhattan(const Node& a, const Node& b) { return abs(a.x - b.x) + abs(a.y - b.y); }
// 对角线距离 int diagonal(const Node& a, const Node& b) { int dx = abs(a.x - b.x); int dy = abs(a.y - b.y); return (dx + dy) + (sqrt(2) - 2) * min(dx, dy); }
2. **优化开放列表检查**:
可以添加一个哈希表来快速检查节点是否已在开放列表中,避免重复添加。
`A*`算法广泛应用于游戏`AI`、机器人路径规划、交通导航等领域,是解决最短路径问题的高效算法。