|
| 1 | +#include <stdio.h> |
| 2 | +#include <limits.h> |
| 3 | + |
| 4 | +#define MAX 100 |
| 5 | + |
| 6 | +int findMinDistance(int dist[], int visited[], int n) { |
| 7 | + int min = INT_MAX, minIndex = -1; |
| 8 | + for (int v = 0; v < n; v++) { |
| 9 | + if (!visited[v] && dist[v] <= min) { |
| 10 | + min = dist[v]; |
| 11 | + minIndex = v; |
| 12 | + } |
| 13 | + } |
| 14 | + return minIndex; |
| 15 | +} |
| 16 | + |
| 17 | +void dijkstra(int graph[MAX][MAX], int n, int start) { |
| 18 | + int dist[n], visited[n]; |
| 19 | + |
| 20 | + for (int i = 0; i < n; i++) { |
| 21 | + dist[i] = INT_MAX; |
| 22 | + visited[i] = 0; |
| 23 | + } |
| 24 | + dist[start] = 0; |
| 25 | + |
| 26 | + for (int count = 0; count < n - 1; count++) { |
| 27 | + int u = findMinDistance(dist, visited, n); |
| 28 | + visited[u] = 1; |
| 29 | + |
| 30 | + for (int v = 0; v < n; v++) { |
| 31 | + if (!visited[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) { |
| 32 | + dist[v] = dist[u] + graph[u][v]; |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + printf("Vertex\tDistance from Source\n"); |
| 38 | + for (int i = 0; i < n; i++) { |
| 39 | + printf("%d\t%d\n", i, dist[i]); |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +int main() { |
| 44 | + int n, start; |
| 45 | + int graph[MAX][MAX]; |
| 46 | + printf("Enter the number of vertices: "); |
| 47 | + scanf("%d", &n); |
| 48 | + |
| 49 | + printf("Enter the adjacency matrix:\n"); |
| 50 | + for (int i = 0; i < n; i++) { |
| 51 | + for (int j = 0; j < n; j++) { |
| 52 | + scanf("%d", &graph[i][j]); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + printf("Enter the starting vertex: "); |
| 57 | + scanf("%d", &start); |
| 58 | + |
| 59 | + dijkstra(graph, n, start); |
| 60 | + return 0; |
| 61 | +} |
0 commit comments