用迪杰斯特拉算法写一段代码
时间: 2023-03-31 11:02:19 浏览: 143
迪杰斯特拉算法代码实现
5星 · 资源好评率100%
好的,以下是使用迪杰斯特拉算法写的代码:
```c
#include <stdio.h>
#include <limits.h>
#define V 9
int minDistance(int dist[], bool sptSet[]) {
int min = INT_MAX, min_index;
for (int v = ; v < V; v++) {
if (!sptSet[v] && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}
void printSolution(int dist[]) {
printf("Vertex \t Distance from Source\n");
for (int i = ; i < V; i++) {
printf("%d \t\t %d\n", i, dist[i]);
}
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
bool sptSet[V];
for (int i = ; i < V; i++) {
dist[i] = INT_MAX;
sptSet[i] = false;
}
dist[src] = ;
for (int count = ; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = ; v < V; v++) {
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
printSolution(dist);
}
int main() {
int graph[V][V] = {{, 4, , , , , , 8, },
{4, , 8, , , , , 11, },
{, 8, , 7, , 4, , , 2},
{, , 7, , 9, 14, , , },
{, , , 9, , 10, , , },
{, , 4, 14, 10, , 2, , },
{, , , , , 2, , 1, 6},
{8, 11, , , , , 1, , 7},
{, , 2, , , , 6, 7, }};
dijkstra(graph, );
return ;
}
```
希望对你有帮助!
阅读全文