 update Dijkstra’s algorithm in case there is 2 shortest paths from strating node to other node

Hey everyone, its my first time here, so be easy on me.

i have a problem i need to solve.

on an undirected/directed graph, i need to rewrite Dijkstra algorithm, so it will output the shortest path with the shortest edge in case there is 2 shortest paths like this: min{2+4,6,2+2+2,1+3+1+1}, then ill choose 6.

i tried to think of a solution but it gets harder when iv been asked to write it on c after many years.

i found this fantastic code, which works, but i have not found any proof that it does consider the number of edges while choose which path to show

it will be great if u can help me find if its consider it or not and if not, maybe help me to try rewrite it with idea.

thanks a lot! ben.

the code:

``````void dijkstra(int G, int n, int startnode)
{

int cost, distance, pred;
int visited, count, mindistance, nextnode, i, j;

//pred[] stores the predecessor of each node
//count gives the number of nodes seen so far
//create the cost matrix
for (i = 0; i<n; i++)
for (j = 0; j<n; j++)
if (G[i][j] == 0)
cost[i][j] = INFINITY;
else
cost[i][j] = G[i][j];

//initialize pred[],distance[] and visited[]
for (i = 0; i<n; i++)
{
distance[i] = cost[startnode][i];
pred[i] = startnode;
visited[i] = 0;
}

distance[startnode] = 0;
visited[startnode] = 1;
count = 1;

while (count<n - 1)
{
mindistance = INFINITY;

//nextnode gives the node at minimum distance
for (i = 0; i<n; i++)
if (distance[i]<mindistance && !visited[i])
{
mindistance = distance[i];
nextnode = i;
}

//check if a better path exists through nextnode
visited[nextnode] = 1;
for (i = 0; i<n; i++)
if (!visited[i])
if (mindistance + cost[nextnode][i]<distance[i])
{
distance[i] = mindistance + cost[nextnode][i];
pred[i] = nextnode;
}
count++;
}

for (i = 0; i<n; i++)
if (i != startnode)
{
printf("Distance of node%d=%d", i, distance[i]);
printf("\nPath=%d", i);
j = i;
do
{
j = pred[j];
printf("<-%d", j);
} while (j != startnode);
printf("\n");
}
}``````
Author: BenSDev
Sort By:
Oldest
|