
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
#include <stdlib.h>
#define MOD 1000000007
#define INF 1000000000
typedef struct {
int node;
int time;
} Pair;
int compare(const void *a, const void *b) {
return ((Pair *)a)->time - ((Pair *)b)->time;
}
int countPaths(int n, int roads[][3], int roadsSize) {
int dist[n], ways[n];
Pair heap[10000];
int heapSize = 0;
int adj[n][n], cost[n][n], degree[n];
for (int i = 0; i < n; i++) {
dist[i] = INF;
ways[i] = 0;
degree[i] = 0;
}
for (int i = 0; i < roadsSize; i++) {
int u = roads[i][0], v = roads[i][1], t = roads[i][2];
adj[u][degree[u]] = v;
cost[u][degree[u]++] = t;
adj[v][degree[v]] = u;
cost[v][degree[v]++] = t;
}
dist[0] = 0;
ways[0] = 1;
heap[heapSize++] = (Pair){0, 0};
while (heapSize) {
qsort(heap, heapSize, sizeof(Pair), compare);
Pair p = heap[--heapSize];
int node = p.node, time = p.time;
for (int i = 0; i < degree[node]; i++) {
int nei = adj[node][i];
int newTime = time + cost[node][i];
if (newTime < dist[nei]) {
dist[nei] = newTime;
ways[nei] = ways[node];
heap[heapSize++] = (Pair){nei, newTime};
} else if (newTime == dist[nei]) {
ways[nei] = (ways[nei] + ways[node]) % MOD;
}
}
}
return ways[n - 1];
}
int main() {
int roads[][3] = {{0,6,7},{0,1,2},{1,2,3},{1,3,3},{6,3,3},{3,5,1},{6,5,1},{2,5,1},{0,4,5},{4,6,2}};
int result = countPaths(7, roads, 10);
printf("Number of shortest paths from 0 to 6: %d\n", result);
return 0;
}