Question

2. Apply Dijkstra’s algorithm as discussed in class to solve the single-source shortest-paths problem for the following graph

0 0
Add a comment Improve this question Transcribed image text
Answer #1


#include <limits.h>
#include <stdio.h>
#include <stdbool.h>
#define v 12
int min_indx(int key[],bool visited[])
{
int min=INT_MAX,min_idx;
for(int i=0;i<v;i++)
{
if(visited[i]==false && key[i]<=min)
{
min=key[i];
min_idx=i;
}
}
return min_idx;
}

void dijkstra(int graph[v][v])
{
int key[v],u,j;
bool visited[v];
for(int i=0;i<v;i++)
{
visited[i]=false;
key[i]=INT_MAX;
}
key[0]=0;
for(int i=0;i<v-1;i++)
{
u=min_indx(key,visited);
visited[u]=true;
for(int j=0;j<v;j++)
{
if(!visited[j] && graph[u][j] && key[u]!=INT_MAX && key[u]+graph[u][j]<key[j])
{
key[j]=key[u]+graph[u][j];
}
}
}
printf("source \tvertex minimal distance\n");
j=0;
for (char i = 'a'; i < 'l'; i++)
{
printf("%c \t %c \t %d\n",'a', i, key[j++]);
}

}

int main()
{
int graph[v][v] = { { 0, 3, 5, 4, 0, 0, 0, 0, 0,0,0,0 },
{ 3, 0, 0, 0, 3, 6, 0, 0, 0,0,0,0 },
{ 5, 0, 0, 2, 0, 0, 4, 0, 0,0,0,0 },
{ 4, 0, 2, 0, 1, 0, 0, 5, 0,0,0,0 },
{ 0, 3, 0, 2, 0, 2, 0, 0, 4,0,0,0 },
{ 0, 6, 0, 0, 2, 0, 0, 0, 0,5,0,0 },
{ 0, 0, 4, 0, 0, 0, 0, 3, 0,0,6,0 },
{ 0, 0, 0, 5, 0, 0, 3, 0, 6,0,7,0 },
{ 0, 0, 0, 0, 4, 0, 0, 6, 0,3,0,5 },
{ 0, 0, 0, 0, 0, 5, 0, 0, 3,0,0,9 },
{ 0, 0, 0, 0, 0, 0, 6, 7, 0,0,0,8 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 5,9,8,0 }};

dijkstra(graph);

return 0;
}

I C:\Users\AMIR KHAN\Desktop\c++\Dijkstra\main.exe source vertex minimal distance a 0 a b 5 a a C d a a е f a a g a 5 7 9 9

source vertex minimal distance

a a 0
a b 3
a c 5
a d 4
a e 5
a f 7
a g 9
a h 9
a i 9
a j 12
a k 15

Add a comment
Know the answer?
Add Answer to:
2. Apply Dijkstra’s algorithm as discussed in class to solve the single-source shortest-paths problem for the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT