Dijkstra's Algorithm Lists
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX 100
#define INF INT_MAX
typedef struct Edge {
int dest;
int weight;
struct Edge* next;
} Edge;
typedef struct Graph {
Edge* edges[MAX];
} Graph;
int dist[MAX];
int pred[MAX];
int visited[MAX];
void create_graph(Graph* graph, int n, int gtype);
void dijkstra(Graph* graph, int n, int source);
void print_shortest_path(int source, int destination);
int main() {
int n, gtype, source;
printf("Enter 1 for undirected graph and -1 for directed graph: ");
scanf("%d", >ype);
printf("Enter the number of vertices: ");
scanf("%d", &n);
Graph graph = { {NULL} };
create_graph(&graph, n, gtype);
printf("Enter the source vertex: ");
scanf("%d", &source);
dijkstra(&graph, n, source);
for (int i = 0; i < n; i++) {
if (i != source) {
printf("Shortest path from vertex %d to vertex %d: ", source, i);
print_shortest_path(source, i);
printf("\n");
}
}
return 0;
}
void create_graph(Graph* graph, int n, int gtype) {
int max_edges, src, dest, weight;
if (gtype == 1)
max_edges = (n * (n - 1)) / 2;
else if (gtype == -1)
max_edges = n * (n - 1);
for (int i = 0; i < max_edges; i++) {
printf("Enter edge %d (source, destination, weight) (to quit enter -1 -1 -1): ", i + 1);
scanf("%d%d%d", &src, &dest, &weight);
if (src == -1 && dest == -1 && weight == -1)
break;
if (src < 0 || dest < 0 || src >= n || dest >= n) {
printf("Invalid source or destination!\n");
i--;
} else {
Edge* edge = (Edge*)malloc(sizeof(Edge));
edge->dest = dest;
edge->weight = weight;
edge->next = graph->edges[src];
graph->edges[src] = edge;
if (gtype == 1) {
edge = (Edge*)malloc(sizeof(Edge));
edge->dest = src;
edge->weight = weight;
edge->next = graph->edges[dest];
graph->edges[dest] = edge;
}
}
}
printf("Adjacency List is:\n");
for (int i = 0; i < n; i++) {
printf("%d: ", i);
for (Edge* edge = graph->edges[i]; edge != NULL; edge = edge->next) {
printf("-> %d (%d) ", edge->dest, edge->weight);
}
printf("\n");
}
}
void dijkstra(Graph* graph, int n, int source) {
int count, mindist, nextnode;
for (int i = 0; i < n; i++) {
dist[i] = INF;
pred[i] = -1;
visited[i] = 0;
}
dist[source] = 0;
visited[source] = 1;
count = 1;
while (count < n) {
mindist = INF;
for (int i = 0; i < n; i++) {
if (dist[i] < mindist && !visited[i]) {
mindist = dist[i];
nextnode = i;
}
}
visited[nextnode] = 1;
for (Edge* edge = graph->edges[nextnode]; edge != NULL; edge = edge->next) {
if (!visited[edge->dest]) {
if (dist[nextnode] + edge->weight < dist[edge->dest]) {
dist[edge->dest] = dist[nextnode] + edge->weight;
pred[edge->dest] = nextnode;
}
}
}
count++;
}
}
void print_shortest_path(int source, int destination) {
if (destination == source) {
printf("%d", source);
} else if (pred[destination] == source) {
printf("%d -> %d ", source, destination);
} else {
print_shortest_path(source, pred[destination]);
printf("-> %d ", destination);
}
}
Comments
Post a Comment