initialize repository of algorithm-template

This commit is contained in:
2025-08-08 23:09:34 +08:00
commit a876627598
19 changed files with 363 additions and 0 deletions

35
dijkstra/dijkstra.cpp Normal file
View File

@@ -0,0 +1,35 @@
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& edge : edges) {
int from = edge[0], to = edge[1], dist = edge[2];
graph[from][to] = dist; // build the graph
}
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; // update non-repeatedly
}
if (next_node < 0 || distance[next_node] > distance[node]) {
next_node = node; // find the node with the smallest moving path
}
}
if (next_node < 0 || distance[next_node] == INT_MAX / 2) {
break; // cannot find the node
}
visited[next_node] = 1;
for (int node = 0; node < n; node++) {
// update the moving paths of the remaining nodes based on the nearest node
distance[node] = min(distance[node], distance[next_node] + graph[next_node][node]);
}
}
return distance[end] == INT_MAX / 2 ? -1 : distance[end];
}
};