Skip to content

Commit 9425378

Browse files
authored
Add Dijkstra in C (#4322)
1 parent 0d7efb9 commit 9425378

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

archive/c/c/dijkstra.c

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <string.h>
4+
#include <limits.h>
5+
#include <stdbool.h>
6+
#include <math.h>
7+
8+
#define MAX_NODES 100
9+
10+
int dijkstra(int graph[MAX_NODES][MAX_NODES], int src, int dest, int n) {
11+
int dist[MAX_NODES];
12+
bool sptSet[MAX_NODES];
13+
14+
for (int i = 0; i < n; i++) {
15+
dist[i] = INT_MAX;
16+
sptSet[i] = false;
17+
}
18+
19+
dist[src] = 0;
20+
21+
for (int count = 0; count < n - 1; count++) {
22+
int min = INT_MAX, min_index;
23+
24+
for (int v = 0; v < n; v++)
25+
if (sptSet[v] == false && dist[v] <= min)
26+
min = dist[v], min_index = v;
27+
28+
int u = min_index;
29+
sptSet[u] = true;
30+
31+
for (int v = 0; v < n; v++)
32+
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
33+
&& dist[u] + graph[u][v] < dist[v])
34+
dist[v] = dist[u] + graph[u][v];
35+
}
36+
37+
return dist[dest] == INT_MAX ? -1 : dist[dest];
38+
}
39+
40+
int main(int argc, char *argv[]) {
41+
if (argc != 4) {
42+
printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n");
43+
return 1;
44+
}
45+
46+
char *matrix = argv[1];
47+
char *src_str = argv[2];
48+
char *dest_str = argv[3];
49+
50+
// Check for empty inputs
51+
if (strlen(matrix) == 0 || strlen(src_str) == 0 || strlen(dest_str) == 0) {
52+
printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n");
53+
return 1;
54+
}
55+
56+
int src = atoi(src_str);
57+
int dest = atoi(dest_str);
58+
59+
long long n = 0;
60+
for (size_t i = 0; matrix[i]; i++) {
61+
if (matrix[i] == ',') n++;
62+
}
63+
n = (long long)sqrt((double)n + 1);
64+
65+
if (src < 0 || dest < 0 || src >= n || dest >= n) {
66+
printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n");
67+
return 1;
68+
}
69+
70+
int graph[MAX_NODES][MAX_NODES] = {0};
71+
char *token = strtok(matrix, ", ");
72+
for (int i = 0; i < n && token; i++) {
73+
for (int j = 0; j < n && token; j++) {
74+
int weight = atoi(token);
75+
if (weight < 0) {
76+
printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n");
77+
return 1;
78+
}
79+
graph[i][j] = weight;
80+
token = strtok(NULL, ", ");
81+
}
82+
}
83+
84+
int result = dijkstra(graph, src, dest, (int)n);
85+
if (result == -1) {
86+
printf("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n");
87+
} else {
88+
printf("%d\n", result);
89+
}
90+
91+
return 0;
92+
}

0 commit comments

Comments
 (0)