35 lines
1.2 KiB
C++
35 lines
1.2 KiB
C++
class Solution {
|
|
public:
|
|
int diskstra(vector<vector<int>>& edges, int n, int start, int end) {
|
|
vector<vector<int>> graph(n, vector<int>(n, INT_MAX / 2));
|
|
// === 建图 ===
|
|
for (auto& [from, to, dist]: edges) {
|
|
graph[from][to] = dist;
|
|
}
|
|
|
|
vector<int> distance(n, INT_MAX/2), visited(n, 0);
|
|
distance[start] = 0;
|
|
while (true) {
|
|
int next_node = -1;
|
|
for (int node = 0; node < n; node++) {
|
|
if (visited[node]) {
|
|
continue; // 不重复更新
|
|
}
|
|
if (next_node < 0 || distance[next_node] > distance[node]) {
|
|
next_node = node; // 寻找移动路径最小的节点
|
|
}
|
|
}
|
|
|
|
if (next_node < 0 || distance[next_node] == INT_MAX / 2) {
|
|
break; // 找不到节点
|
|
}
|
|
|
|
visited[next_node] = 1;
|
|
for (int node = 0; node < n; node++) {
|
|
// 根据最近节点路径更新其余节点移动路径
|
|
distance[node] = min(distance[node], distance[next_node] + graph[next_node][node]);
|
|
}
|
|
}
|
|
return distance[end] == INT_MAX / 2 ? -1 : distance[end];
|
|
}
|
|
}; |