dijkstra最短路径算法代码用C++写
时间: 2023-10-16 22:11:09 浏览: 91
Sure, here's an example implementation of Dijkstra's algorithm in C:
```
#define INF 1000000000
#define N 1000
int graph[N][N]; // adjacency matrix for the graph
int dist[N]; // shortest distance from start to each vertex
bool visited[N]; // whether each vertex has been visited
void dijkstra(int start) {
for (int i = 0; i < N; i++) {
dist[i] = INF;
visited[i] = false;
}
dist[start] = 0;
for (int i = 0; i < N; i++) {
int min_dist = INF;
int min_index = -1;
for (int j = 0; j < N; j++) {
if (dist[j] < min_dist && !visited[j]) {
min_dist = dist[j];
min_index = j;
}
}
if (min_index == -1) break;
visited[min_index] = true;
for (int j = 0; j < N; j++) {
if (graph[min_index][j] != INF && dist[min_index] + graph[min_index][j] < dist[j]) {
dist[j] = dist[min_index] + graph[min_index][j];
}
}
}
}
```
I hope that helps! Let me know if you have any other questions.
阅读全文