图示:
代码:
#include<iostream>
#include<sstream>
#include<string>
#include<vector>
#include<map>
using namespace std;
vector<vector<int>> buildgraph(vector<vector<int>>&edges,int n) {
vector<vector<int>> graph(n, vector<int>(n, INT_MAX));
for (int i = 0; i < edges.size(); i++) {
int m = edges[i][0], k = edges[i][1], w = edges[i][2];
graph[m][k] = w;
}
return graph;
}
vector<int> dijkstra(vector<vector<int>>& edges,int n) {
vector<vector<int>> adjacent_matrix = buildgraph(edges, n);
vector<int> point(n, INT_MAX);
vector<int> path(n, -1);
path[0] = 0; point[0] = 0;
for (int i = 0; i < n; i++) {
int index = 0, min_w = INT_MAX;
for (int j = 0; j < n; j++) {
if (point[j] == -1) continue;
if (point[j] < min_w) {
min_w = point[j];
index = j;
}
}
for (int j = 0; j < n; j++) {
if (adjacent_matrix[index][j] == INT_MAX)continue;
int temp = adjacent_matrix[index][j] + point[index];
if (point[j] > temp) {
point[j] = temp;
path[j] = index;
}
}
point[index] = -1;
}
return path;
}
int main() {
vector<vector<int>>edges = { {0,1,9},{0,2,14},{0,3,15},{1,4,24},{2,4,18},{2,5,30},{3,5,20},{3,7,44},{4,5,2},{4,7,19},{5,6,11},{5,7,16},{6,7,6} };
vector<int> res = dijkstra(edges, 8);
return 0;
}