最近刷题遇到了1个最短路算法的题: https://leetcode-cn.com/problems/network-delay-time/,我就在想有没有一个最佳的通用的朴素Dijkstra的C++实现。看了一些解答,有一个很经典,核心逻辑20行左右,没有任何冗余操作,像是搞ACMer同学的风格。核心实现如下:
#include
#include
#include
using namespace std;
/**
* @param graph, 图的邻接矩阵表示
* @param start, 起始点
* @return start到所有点的最短距离
*/
vector<int> dijkstra(vector<vector<int>> &graph, int start)
{
const int INF = 0x3f3f3f3f; // 经典最大值,松弛其他边不溢出
const int num = graph.size();
vector<int> distances(num, INF);
vector<bool> visited(num, false);
distances[start] = 0; // 起始点到自己的距离
for (int i = 0; i < num; i++) {
// 在未确定到start的最短路的的点里, 找离start最近的点
int t = -1;
for (int j = 0; j < num; j++) {
if (!visited[j] && (t == -1 || graph[j] < graph[t])) {
t = j;
}
}
visited[t] = true; // t号点的最短路已确定
// 松弛操作,用t号点的更新所有点到start的最短路
for (int j = 0; j < num; j++) {
distances[j] = min(distances[j], distances[t] + graph[t][j]);
}
}
return distances;
}
int main()
{
int N = 65536;
vector<vector<int>> graph = {
{0, 1, 5, N, N, N, N, N, N},
{1, 0, 3, 7, 5, N, N, N, N},
{5, 3, 0, N, 1, 7, N, N, N},
{N, 7, N, 0, 2, N, 3, N, N},
{N, 5, 1, 2, 0, 3, 6, 9, N},
{N, N, 7, N, 3, 0, N, 5, N},
{N, N, N, 3, 6, N, 0, 2, 7},
{N, N, N, N, 9, 5, 2, 0, 4},
{N, N, N, N, N, N, 7, 4, 0}
};
vector<int> ans = dijkstra(graph, 0);
for (auto &i : ans) {
// 0 1 4 7 5 8 10 12 16
printf("%d ", i);
}
return 0;
}