forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dijsktra.c
122 lines (116 loc) · 1.7 KB
/
Dijsktra.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/* Dijkstra's Algorithm and code in C */
#include<stdio.h>
#include<stdlib.h>
void main(){
int size;
//Enter the maximum size of the node
//for cost distance and path
printf("Enter the maximum size of node:");
scanf("%d",&size);
int cost[size][size],distance[size],path[size][size],n,v,p,row,column,min,index=1,i,j;
//use enters no of nodes
printf("Enter no of nodes : ");
scanf("%d",&n);
//user enters cost of matrix
printf("Enter cost matrix : ");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
}
}
//user enters node to be visited
printf("Enter node to visit : ");
scanf("%d",&v);
//user enters no of paths for particular node
printf("Enter paths for the selected node : ");
scanf("%d",&p);
//path matrix
printf("Enter path matrix \n");
for(i=1;i<=p;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&path[i][j]);
}
}
for(i=1;i<=p;i++)
{
distance[i]=0;
row=1;
for(j=1;j<n;j++)
{
if(row!=v)
{//till i visit the last node
column=path[i][j+1];
distance[i] = distance[i]+cost[row][column];
}
row=column;
}
}
//which distance to be considered
min=distance[1];
for(i=1;i<=p;i++)
{
if(distance[i]<=min)
{
min=distance[i];
index=i;
}
}
printf("min distance is %d\n",min);
printf("min distance path is\n");
for(i=1;i<=n;i++)
{
if(path[index][i]!=0)
printf("--->%d", path[index][i]);
}
}
/*
Sample Input Output
Enter the size of the node : 10
Enter no of nodes : 5
Enter cost matrix : 0
4
0
8
0
4
0
3
0
0
0
3
0
4
0
8
0
4
0
7
0
0
0
7
0
Enter node to visit : 5
Enter paths for the selected node : 2
Enter path matrix
1
2
3
4
5
1
4
5
0
0
min distance is 15
min distance path is
--->1--->4--->5
Time Complexity : O(N^2)
*/