1 前言
从某顶点出发,沿图的边到达另一顶点所经过的路径中,各边上权值之和最小的一条路径叫做最短路径。解决最短路的问题有以下算法
- Dijkstra 算法
- Bellman-Ford 算法
- SPFA 算法(Bellman-Ford 算法的优化算法)
- Floyd 算法等
给出一些名词解释:
- 单源最短路径:从图中某个顶点到图其他各顶点的最短路径
- Relax 松弛:这是最短路径算法里面最关键的一步(我也不清楚怎么解释,自行体会吧)
- 邻接矩阵与邻接表:都是表示图的方法,很简单,自行搜索
- 负权值环:最简单的负权值环就是,自己到自己的一个负权值边(构成了一个回环);如此以来不断地通过这个环(路径),那我岂不可以无限缩短距离,
真是鬼才
本文没有详细介绍(写起来太麻烦,还不如直接看视频容易理解)但是有推荐视频或文章,这里主要有我的具体实现,仅供参考
最后推荐一个 Github 项目,这是我在找资料的时候看到的,里面的算法实现均为 JAVA
语言,根据他的实现,本文提供 C++
的实现,保持尽量了几种算法风格的统一,如发现错误,请指正~
2 Dijkstra 算法
关于这个算法,推荐看一下这个 Video 讲解,我在这里也就不介绍了,主要看实现
关键词:
- 单源最短路径
- 贪心算法
缺点:
- 图中有负权值边时往往不适用,但可以选择 Bellman-Ford 算法代替。注:有负权值边导致出现负权值环才会使 Dijkstra 失效,而 Bellman-Ford 可以定位到负权值环,并且解决这个问题,后面会提到。
2.1 邻接矩阵实现
效率分析,我们用 V
代表顶点数, E
代表边数
- 时间复杂度 O ( V 2 ) O(V^2) O(V2)
C++ 实现,一般来说需要以下四个完成
graph
是由邻接矩阵表示的图,相当于一个二维数组vistied
负责维护访问过的节点,没访问 false,访问了设置 truedis
负责维护由源点到每个顶点的最短距离path
保存的是最短路径,在这里我是维护了完整的路径,但实际上只需要维护前一个点就可以了
#include <vector>
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <limits>
using namespace std;
#define POSITIVE_INF (numeric_limits<int>::max()) // <limits> 里定义的
void Dijkstra(vector<vector<double> > &graph, vector<double> &dis, vector<int> *path, const int vNum, const int vStart) {
fill_n(dis.begin(), vNum, POSITIVE_INF);
dis[vStart] = 0;
bool *visited = new bool[vNum];
fill_n(visited, vNum, false);
for (int k = 0; k < vNum; k++) {
int minNum = POSITIVE_INF, minIndex = -1;
for (int i = 0; i < vNum; i++) { //找一个最小距离的顶点
if (false == visited[i] && dis[i] < minNum) {
minNum = dis[i];
minIndex = i;
}
}
visited[minIndex] = true;
for (int j = 0; j < vNum; j++) {
if (true == visited[j]) continue; //已经访问过的跳过
if (graph[minIndex][j] == POSITIVE_INF) continue; //通过 minIndex 无法到达 j,跳过
if (dis[j] > dis[minIndex] + graph[minIndex][j]) { //Relax 操作
dis[j] = dis[minIndex] + graph[minIndex][j]; //更新最短距离
path[j] = path[minIndex]; //更新路径
path[j].push_back(minIndex);
}
}
}
delete[]visited;
}
void AddEdge(vector<vector<double> > &graph, int from, int to, double cost) {
graph[from][to] = cost;
}
void PrintPath(vector<int>& path, int self) {
for (int v : path) {
cout << v << "->";
}
cout << self << endl;
}
void PrintMatrix(vector<vector<double> > &graph) {
for (auto level : graph) {
cout << "[";
for (auto v : level) {
if (v >= POSITIVE_INF) cout << setw(5) << left << "inf";
else cout << fixed << setprecision(0) << setw(5) << left << v;
}
cout << "]\n";
}
cout << endl;
}
int main() {
int vNum = 5, vStart = 0;
vector<vector<double> > graph(vNum, vector<double>(vNum, POSITIVE_INF));
vector<double> dis(vNum, POSITIVE_INF); //记录源点到其他点的最短距离
vector<int>* path = new vector<int>[vNum]; //记录最短距离经过的路径
for(int i = 0; i < vNum; i++) AddEdge(graph, i, i, 0);
AddEdge(graph, 0, 1, 6);
AddEdge(graph, 0, 3, 1);
AddEdge(graph, 1, 0, 6);
AddEdge(graph, 1, 2, 5);
AddEdge(graph, 1, 3, 2);
AddEdge(graph, 1, 4, 2);
AddEdge(graph, 2, 1, 5);
AddEdge(graph, 2, 4, 5);
AddEdge(graph, 3, 0, 1);
AddEdge(graph, 3, 1, 2);
AddEdge(graph, 3, 4, 1);
AddEdge(graph, 4, 1, 2);
AddEdge(graph, 4, 2, 5);
AddEdge(graph, 4, 3, 1);
PrintMatrix(graph);
Dijkstra(graph, dis, path, vNum, vStart);
for (int i = 0; i < vNum; i++) {
cout << "From " << vStart << " to " << i << " distance: " << setw(5) << dis[i];
PrintPath(path[i], i);
}
delete[]path;
system("pause");
// From 0 to 0 distance: 0 0
// From 0 to 1 distance: 3 0->3->1
// From 0 to 2 distance: 7 0->3->4->2
// From 0 to 3 distance: 1 0->3
// From 0 to 4 distance: 2 0->3->4
}
2.2 邻接表实现
效率分析,我们用 V
代表顶点数, E
代表边数
- 简单实现,时间复杂度 O ( E V ) O(EV) O(EV)
- 优先队列(最小堆),时间复杂度 O ( E l o g V ) O(ElogV) O(ElogV)
C++ 实现,不懂看注释
#include <vector>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <limits>
#include <queue>
using namespace std;
#define POSITIVE_INF (numeric_limits<int>::max()) // <limits> 里定义的
struct Edge {
int from;
int to;
double cost;
Edge(int from, int to, double cost) :from(from), to(to), cost(cost) {}
};
typedef pair<double, int> Node; // first 为到该顶点的最短距离,second 为顶点编号,这个数据结构用于优先队列里排序用的
void AddEdge(vector<Edge> *graph, int from, int to, double cost) {
graph[from].push_back(Edge(from, to, cost));
}
//使用优先队列实现,时间复杂度 O((ElogV)
void Dijkstra_PQ(vector<Edge> *graph, vector<double> &dis, vector<int> *path, const int vNum, const int vStart) {
fill_n(dis.begin(), vNum, POSITIVE_INF);
dis[vStart] = 0;
priority_queue<Node, vector<Node>, greater<Node> > q; //距离小的先出队,比较的是 Node.frist
q.push(Node(0, vStart));
bool *visited = new bool[vNum]; //设置已访问过的数组
fill_n(visited, vNum, false);
while (!q.empty()) {
Node node = q.top(); q.pop();
visited[node.second] = true;
if (dis[node.second] < node.first) continue; //队列里的这个节点最短距离的值旧了,跳过
for (Edge edge : graph[node.second]) {
if (visited[edge.to]) continue; //已经访问过的节点则跳过
if (dis[edge.to] > dis[edge.from] + edge.cost) { //Relax 操作
dis[edge.to] = dis[edge.from] + edge.cost; //更新 distance
path[edge.to] = path[edge.from]; //更新路径
path[edge.to].push_back(edge.from);
q.push(Node(dis[edge.to], edge.to));
}
}
}
delete[]visited;
}
//简单实现,时间复杂度 O(EV)
void Dijkstra_Simple(vector<Edge> *graph, vector<double> &dis, vector<int> *path, const int vNum, const int vStart) {
fill_n(dis.begin(), vNum, POSITIVE_INF);
dis[vStart] = 0;
bool *visited = new bool[vNum];
fill_n(visited, vNum, false);
for (int k = 0; k < vNum; k++) {
int minNum = POSITIVE_INF, minIndex = -1;
for (int i = 0; i < vNum; i++) { //找一个最小的
if (false == visited[i] && dis[i] < minNum) {
minNum = dis[i];
minIndex = i;
}
}
visited[minIndex] = true;
for (Edge edge : graph[minIndex]) {
if (visited[edge.to]) continue; //已经访问过的节点则跳过
if (dis[edge.to] > dis[edge.from] + edge.cost) { //Relax 操作
dis[edge.to] = dis[edge.from] + edge.cost; //更新 distance
path[edge.to] = path[edge.from]; //更新路径
path[edge.to].push_back(edge.from);
}
}
}
delete[]visited;
}
void PrintPath(vector<int>& path, int self) {
for (int v : path) {
cout << v << "->";
}
cout << self << endl;
}
int main() {
int vNum = 5, vStart = 0; // vNum 顶点数量,vStart 起始点编号
vector<Edge> *graph = new vector<Edge>[vNum]; //邻接表表示的图
vector<double> dis(vNum, POSITIVE_INF); //最短距离
vector<int> *path = new vector<int>[vNum]; //存储记录的最短路径
AddEdge(graph, 0, 1, 6);
AddEdge(graph, 0, 3, 1);
AddEdge(graph, 1, 0, 6);
AddEdge(graph, 1, 2, 5);
AddEdge(graph, 1, 3, 2);
AddEdge(graph, 1, 4, 2);
AddEdge(graph, 2, 1, 5);
AddEdge(graph, 2, 4, 5);
AddEdge(graph, 3, 0, 1);
AddEdge(graph, 3, 1, 2);
AddEdge(graph, 3, 4, 1);
AddEdge(graph, 4, 1, 2);
AddEdge(graph, 4, 2, 5);
AddEdge(graph, 4, 3, 1);
// Dijkstra_PQ(graph, dis, path, vNum, vStart);
Dijkstra_Simple(graph, dis, path, vNum, vStart);
for (int i = 0; i < vNum; i++) {
cout << "From " << vStart << " to " << i << " distance: " << setw(5) << left << dis[i];
PrintPath(path[i], i);
}
delete[]graph;
delete[]path;
system("pause");
// From 0 to 0 distance: 0 0
// From 0 to 1 distance: 3 0->3->1
// From 0 to 2 distance: 7 0->3->4->2
// From 0 to 3 distance: 1 0->3
// From 0 to 4 distance: 2 0->3->4
}
3 Bellman Ford 算法
推荐食用这个 Video 以及这篇 Blog,我这里简单讲一下怎么解决负权值的问题。按照视频里说的,事实上就是将核心代码再跑一遍,如果还能进行松弛操作,那证明这里出现了负权值环了,然后可以不断扩散出去,能松弛的就代表受到负权值环的影响。
关键词:
- 单源最短路径
- 解决负权值环问题
缺点:
- 时间复杂度过高,但可进行优化,即后面会提到的 SPFA 算法
3.1 邻接矩阵实现
效率分析,我们用 V
代表顶点数, E
代表边数
- 时间复杂度 O ( V 3 ) O(V^3) O(V3)
#include <vector>
#include <iomanip>
#include <iostream>
#include <queue>
#include <limits>
using namespace std;
#define POSITIVE_INF (numeric_limits<int>::max())
#define NEGATIVE_INF (numeric_limits<int>::min())
void BellmanFord(vector<vector<double> > &graph, vector<double> &dis, vector<int>* path ,const int vNum, const int vStart) {
fill_n(dis.begin(), vNum, POSITIVE_INF);
dis[vStart] = 0;
for (int k = 0; k < vNum - 1; k++) { // For each vertex, apply relaxation for all the edges
for (int i = 0; i < vNum; i++) {
for (int j = 0; j < vNum; j++) {
if (graph[i][j] == POSITIVE_INF) continue; // 没有 i 到 j 的边,跳过
if (dis[j] > dis[i] + graph[i][j]) { // Relax 操作
dis[j] = dis[i] + graph[i][j]; // 更新最短距离
path[j] = path[i]; // 更新路径
path[j].push_back(i);
}
}
}
}
for (int k = 0; k < vNum - 1; k++) { // Run algorithm a second time to detect which nodes are part of a negative cycle.
for (int i = 0; i < vNum; i++) {
for (int j = 0; j < vNum; j++) {
if (graph[i][j] == POSITIVE_INF) continue; // 没有 i 到 j 的边,跳过
if (dis[j] == NEGATIVE_INF) continue;
if (dis[j] > dis[i] + graph[i][j]) {
dis[j] = NEGATIVE_INF;
path[j].clear();
}
}
}
}
}
void AddEdge(vector<vector<double> > &graph, int from, int to, double cost) {
graph[from][to] = cost;
}
void PrintPath(vector<int>& path, int self) {
for (int v : path) {
cout << v << "->";
}
cout << self << endl;
}
void PrintMatrix(vector<vector<double> > &graph) {
for (auto level : graph) {
cout << "[";
for (auto v : level) {
if (v >= POSITIVE_INF) cout << setw(5) << left << "inf";
else cout << fixed << setprecision(0) << setw(5) << left << v;
}
cout << "]\n";
}
cout << endl;
}
int main() {
int vNum = 9, vStart = 0;
vector<vector<double> > graph(vNum, vector<double>(vNum, POSITIVE_INF));
vector<double> dis(vNum, POSITIVE_INF);
vector<int>* path = new vector<int>[vNum];
for (int i = 0; i < vNum; i++) AddEdge(graph, i, i, 0);
AddEdge(graph, 0, 1, 1);
AddEdge(graph, 1, 2, 1);
AddEdge(graph, 2, 4, 1);
AddEdge(graph, 4, 3, -3);
AddEdge(graph, 3, 2, 1);
AddEdge(graph, 1, 5, 4);
AddEdge(graph, 1, 6, 4);
AddEdge(graph, 5, 6, 5);
AddEdge(graph, 6, 7, 4);
AddEdge(graph, 5, 7, 3);
PrintMatrix(graph);
BellmanFord(graph, dis, path, vNum, vStart);
for (int i = 0; i < vNum; i++) {
cout << "From " << vStart << " to " << i << " distance: ";
if (dis[i] == POSITIVE_INF) cout << left << setw(6) << "+inf";
else if (dis[i] == NEGATIVE_INF) cout << left << setw(6) << "-inf";
else cout << left << setw(6) << dis[i];
PrintPath(path[i], i);
}
delete[]path;
system("pause");
}
3.2 邻接表实现
效率分析,我们用 V
代表顶点数, E
代表边数
- 时间复杂度 O ( E V ) O(EV) O(EV)
#include <vector>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <limits>
using namespace std;
#define POSITIVE_INF (numeric_limits<int>::max())
#define NEGATIVE_INF (numeric_limits<int>::min())
struct Edge {
int from;
int to;
double cost;
Edge(int from, int to, double cost) :from(from), to(to), cost(cost) {}
};
void AddEdge(vector<Edge>* graph, int from, int to, double cost) {
graph[from].push_back(Edge(from, to, cost));
}
void BellmanFord(vector<Edge>* graph, vector<double> &dis, vector<int>* path, const int vNum, const int vStart) {
fill_n(dis.begin(), vNum, POSITIVE_INF);
dis[vStart] = 0;
for (int k = 0; k < vNum - 1; k++) { // For each vertex, apply relaxation for all the edges
for (int i = 0; i < vNum; i++) {
for (Edge edge : graph[i]) {
if (dis[edge.from] + edge.cost < dis[edge.to]) {
dis[edge.to] = dis[edge.from] + edge.cost;
path[edge.to] = path[edge.from];
path[edge.to].push_back(edge.from);
}
}
}
}
for (int k = 0; k < vNum - 1; k++) { // Run algorithm a second time to detect which nodes are part of a negative cycle.
for (int i = 0; i < vNum; i++) {
for (Edge edge : graph[i]) {
if (dis[edge.from] + edge.cost < dis[edge.to]) {
dis[edge.to] = NEGATIVE_INF;
path[edge.to].clear();
}
}
}
}
}
void PrintPath(vector<int>& path, int self) {
for (int v : path) {
cout << v << "->";
}
cout << self << endl;
}
void PrintEdge(vector<Edge> *graph, int vNum) {
for (int i = 0; i < vNum; i++) {
for (Edge edge : graph[i]) {
cout << "Edge " << edge.from << " to " << edge.to << " , cost: " << edge.cost << endl;
}
}
cout << endl;
}
int main() {
int vNum = 9, vStart = 0;
vector<Edge> *graph = new vector<Edge>[vNum];
vector<double> dis(vNum, POSITIVE_INF);
vector<int>* path = new vector<int>[vNum];
AddEdge(graph, 0, 1, 1);
AddEdge(graph, 1, 2, 1);
AddEdge(graph, 2, 4, 1);
AddEdge(graph, 4, 3, -3);
AddEdge(graph, 3, 2, 1);
AddEdge(graph, 1, 5, 4);
AddEdge(graph, 1, 6, 4);
AddEdge(graph, 5, 6, 5);
AddEdge(graph, 6, 7, 4);
AddEdge(graph, 5, 7, 3);
PrintEdge(graph, vNum);
BellmanFord(graph, dis, path, vNum, vStart);
for (int i = 0; i < vNum; i++) {
cout << "From " << vStart << " to " << i << " distance: ";
if (dis[i] == POSITIVE_INF) cout << left << setw(6) << "+inf";
else if (dis[i] == NEGATIVE_INF) cout << left << setw(6) << "-inf";
else cout << left << setw(6) << dis[i];
PrintPath(path[i], i);
}
delete[]graph;
delete[]path;
system("pause");
// [0 1 inf inf inf inf inf inf inf ]
// [inf 0 1 inf inf 4 4 inf inf ]
// [inf inf 0 inf 1 inf inf inf inf ]
// [inf inf 1 0 inf inf inf inf inf ]
// [inf inf inf -3 0 inf inf inf inf ]
// [inf inf inf inf inf 0 5 3 inf ]
// [inf inf inf inf inf inf 0 4 inf ]
// [inf inf inf inf inf inf inf 0 inf ]
// [inf inf inf inf inf inf inf inf 0 ]
// From 0 to 0 distance: 0 0
// From 0 to 1 distance: 1 0->1
// From 0 to 2 distance: -inf 2
// From 0 to 3 distance: -inf 3
// From 0 to 4 distance: -inf 4
// From 0 to 5 distance: 5 0->1->5
// From 0 to 6 distance: 5 0->1->6
// From 0 to 7 distance: 8 0->1->5->7
// From 0 to 8 distance: +inf 8
}
3.3 一些优化方法
优化一:循环的提前跳出
通常 Bellman Ford 算法经常会在未达到 n-1 轮松弛前就已经计算出最短路。因此每一轮执行后,若没有执行松弛操作则算法就可以停止了,则我们可以添加一个标志位 flag
,如下所示
for (int k = 0; k < vNum - 1; k++) { // 一共是执行 vNum - 1 轮
bool flag = false;
for (int i = 0; i < vNum; i++) {
for (Edge edge : graph[i]) {
if (dis[edge.from] + edge.cost < dis[edge.to]) {
dis[edge.to] = dis[edge.from] + edge.cost;
path[edge.to] = path[edge.from];
path[edge.to].push_back(edge.from);
flag = true; // 更新了 dis 则标志设 true
}
}
}
if(!flag) break; // dis 未更新,跳出循环
}
优化二:SPFA 的算法,即避免冗余的计算
松弛操作必定只会发生在最短路径前导节点松弛成功过的节点上,则用一个队列记录松弛过的节点,可以避免了冗余计算,这即是 SPFA 算法的核心,下一节将介绍 SPFA 的实现
4 SPFA 算法
通过前面我们知道 SPFA 算法是优化后的 Bellman Ford 算法,如何实现?以下引用自百度百科-SPFA算法
动态逼近法:设立一个先进先出的队列用来保存待优化的结点,优化时每次取出队首结点u,并且用u点当前的最短路径估计值对离开u点所指向的结点v进行松弛操作,如果v点的最短路径估计值有所调整,且v点不在当前的队列中,就将v点放入队尾
关于 SPFA 算法,我是仿照百度百科里实现的,里面检测到环的时候将会直接中止算法,为了与前面保持一致,我做了一些改进。与前面一样,改进之后能检测出哪些节点会受到负权值环的影响,受到影响的其最后输出的最短距离为 -inf
。
注:此代码可能有误,请大家小心参考
#include <vector>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <limits>
#include <queue>
using namespace std;
#define POSITIVE_INF (numeric_limits<int>::max())
#define NEGATIVE_INF (numeric_limits<int>::min())
struct Edge {
int from;
int to;
double cost;
Edge(int from, int to, double cost) :from(from), to(to), cost(cost) {}
};
void AddEdge(vector<Edge>* graph, int from, int to, double cost) {
graph[from].push_back(Edge(from, to, cost));
}
void SPFA(vector<Edge>* graph, vector<double> &dis, vector<int>* path, const int vNum, const int vStart) {
fill_n(dis.begin(), vNum, POSITIVE_INF);
dis[vStart] = 0;
queue<int> q;
q.push(vStart);
vector<bool> inQueue(vNum, false); //记录某顶点是否在队列中
inQueue[vStart] = true;
vector<int> cnt(vNum, 0); //记录某顶点进入队列的次数
cnt[vStart] = 1;
while (!q.empty()) {
int v = q.front(); q.pop();
inQueue[v] = false;
for (Edge edge : graph[v]) {
if (dis[edge.to] == NEGATIVE_INF) continue; //已经被负权环路感染
if (dis[edge.from] == NEGATIVE_INF) { //将要被负权环路感染
dis[edge.to] = NEGATIVE_INF;
path[edge.to].clear();
if(!inQueue[edge.to]) {
q.push(edge.to);
inQueue[edge.to] = true;
}
continue;
}
if (dis[edge.to] > dis[edge.from] + edge.cost) { //松弛
dis[edge.to] = dis[edge.from] + edge.cost;
path[edge.to] = path[edge.from];
path[edge.to].push_back(edge.from);
if (!inQueue[edge.to]) {
cnt[edge.to]++;
if (cnt[edge.to] == vNum) { //出现负权值
dis[edge.to] = NEGATIVE_INF;
path[edge.to].clear();
}
q.push(edge.to);
inQueue[edge.to] = true;
}
}
}
}
}
void PrintPath(vector<int>& path, int self) {
for (int v : path) {
cout << v << "->";
}
cout << self << endl;
}
void PrintEdge(vector<Edge> *graph, int vNum) {
for (int i = 0; i < vNum; i++) {
for (Edge edge : graph[i]) {
cout << "Edge " << edge.from << " to " << edge.to << " , cost: " << edge.cost << endl;
}
}
cout << endl;
}
int main() {
int vNum = 9, vStart = 0;
vector<Edge> *graph = new vector<Edge>[vNum];
vector<double> dis(vNum, POSITIVE_INF);
vector<int>* path = new vector<int>[vNum];
AddEdge(graph, 0, 1, 1);
AddEdge(graph, 1, 2, 1);
AddEdge(graph, 2, 4, 1);
AddEdge(graph, 4, 3, -3);
AddEdge(graph, 3, 2, 1);
AddEdge(graph, 1, 5, 4);
AddEdge(graph, 1, 6, 4);
AddEdge(graph, 5, 6, 5);
AddEdge(graph, 6, 7, 4);
AddEdge(graph, 5, 7, 3);
PrintEdge(graph, vNum);
SPFA(graph, dis, path, vNum, vStart);
for (int i = 0; i < vNum; i++) {
cout << "From " << vStart << " to " << i << " distance: ";
if (dis[i] == POSITIVE_INF) cout << left << setw(6) << "+inf";
else if (dis[i] == NEGATIVE_INF) cout << left << setw(6) << "-inf";
else cout << left << setw(6) << dis[i];
PrintPath(path[i], i);
}
delete[]graph;
delete[]path;
system("pause");
}
5 Floyd-Warshall 算法
先推荐 Video,这是本文实现的最后一个算法,这也是大家一般学习到的多源最短路径算法,需要注意的是
dis
数组上升到了二维(毕竟是多源最短路径)- 保存路径的不再是
pre
数组,而是next
数组,看完视频后好好想想他们之间的区别
5.1 邻接矩阵实现
#include <vector>
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <limits>
using namespace std;
#define POSITIVE_INF (numeric_limits<int>::max())
#define NEGATIVE_INF (numeric_limits<int>::min())
#define DOES_NOT_EXIST -1
#define REACHES_NEGATIVE_CYCLE -2
void AddEdge(vector<vector<double> > &graph, int from, int to, double cost) {
graph[from][to] = cost;
}
void Floyd(vector<vector<double> > &graph, vector<vector<double> > &dis, vector<vector<int> > &next, const int vNum) {
dis = graph; //赋值操作,不是 java 里的指向对象哈
for (int i = 0; i < vNum; i++) { //pre 数组初始化
for (int j = 0; j < vNum; j++) {
if (graph[i][j] != POSITIVE_INF) next[i][j] = j;
}
}
for (int k = 0; k < vNum; k++) {
for (int i = 0; i < vNum; i++) {
for (int j = 0; j < vNum; j++) {
if (dis[i][k] == POSITIVE_INF || dis[k][j] == POSITIVE_INF) continue;
if (dis[i][j] > dis[i][k] + dis[k][j]) {
dis[i][j] = dis[i][k] + dis[k][j];
next[i][j] = next[i][k];
}
}
}
}
// Identify negative cycles by propagating the value 'NEGATIVE_INFINITY'
// to every edge that is part of or reaches into a negative cycle.
for (int k = 0; k < vNum; k++) {
for (int i = 0; i < vNum; i++) {
for (int j = 0; j < vNum; j++) {
if (dis[i][k] == POSITIVE_INF || dis[k][j] == POSITIVE_INF) continue;
if (dis[i][j] == NEGATIVE_INF) continue;
if (dis[i][j] > dis[i][k] + dis[k][j]) {
dis[i][j] = NEGATIVE_INF;
next[i][j] = REACHES_NEGATIVE_CYCLE;
}
}
}
}
}
template<typename T>
void PrintMatrix(vector<vector<T> > &graph) {
for (auto level : graph) {
cout << "[";
for (auto v : level) {
if (v >= POSITIVE_INF) cout << setw(5) << left << "+inf";
else if ( v <= NEGATIVE_INF) cout << setw(5) << left << "-inf";
else cout << fixed << setprecision(0) << setw(5) << left << v;
}
cout << "]\n";
}
cout << endl;
}
int main() {
int vNum = 7;
vector<vector<double> > graph(vNum, vector<double>(vNum, POSITIVE_INF)); //图中所有值初始化为 POSITIVE_INF 即两点不联通
vector<vector<double> > dis(vNum, vector<double>(vNum, POSITIVE_INF)); //dis[i][j] 记录当前 i 到 j 的最短距离,是动态规划中的 dp 数组
vector<vector<int> > next(vNum, vector<int>(vNum, DOES_NOT_EXIST)); //保存 i 到 j 当前最短路径的下一个节点
//设置图
for (int i = 0; i < vNum; i++) graph[i][i] = 0;
AddEdge(graph, 0, 1, 2);
AddEdge(graph, 0, 2, 5);
AddEdge(graph, 0, 6, 10);
AddEdge(graph, 1, 2, 2);
AddEdge(graph, 1, 4, 11);
AddEdge(graph, 2, 6, 2);
AddEdge(graph, 6, 5, 11);
AddEdge(graph, 4, 5, 1);
AddEdge(graph, 5, 4, -2);
PrintMatrix(graph);
Floyd(graph, dis, next, vNum);
PrintMatrix(dis);
PrintMatrix(next);
system("pause");
}
6 最后我想说的
我的实现并不是标准,仅供大家参考,如果你有更好的实现也欢迎在评论区留言。如果有误请立即联系我,感谢。
然后,本文只列举了 4 种算法,还有其他的并未提及,所以可能还会有续篇~
7 参考资料
[1] 百度百科/Bellman-Ford算法 https://baike.baidu.com/item/Bellman-Ford算法
[2] Bellman-Ford算法(解决负权边)https://blog.csdn.net/wtyvhreal/article/details/43450727
[3] SPFA算法 https://baike.baidu.com/item/SPFA%E7%AE%97%E6%B3%95
[4] Github/williamfiset https://github.com/williamfiset/Algorithms
[5] 最短路径搜索之A*算法 https://blog.csdn.net/yuxuan20062007/article/details/80914210