-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQ1_Assignment.cpp
More file actions
105 lines (88 loc) · 1.61 KB
/
Q1_Assignment.cpp
File metadata and controls
105 lines (88 loc) · 1.61 KB
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
"Q.1: Given order of n matrices, find the minimum multiplication operations required
for multiplying n matrices."
#include<iostream>
using namespace std;
#define INFINITY 1000
#define MAX_NODES 1024
//int n,dist[MAX_NODES][MAX_NODES];
typedef enum { permanent,tentative } label_type;
struct state
{
int predecessor;
int length;
label_type label;
};
void shortest_path(int s,int t,int n, int ** dist)
{
state* st=new state[n];
int i,k,min;
state* p;
for( i=0; i<n ; i++)
{
p = &st[i];
p->predecessor = -1;
p->length=INFINITY;
p->label = tentative;
}
st[t].length=0;
st[t].label=permanent;
k=t;
do
{
for(i=0;i<n;i++)
if(dist[k][i]!=0 && st[i].label==tentative)
{
if((st[k].length + dist[k][i])<st[i].length)
{
st[i].predecessor=k;
st[i].length=st[k].length+dist[k][i];
}
}
k=0;min=INFINITY;
for(i=0;i<n;i++)
if(st[i].label==tentative && st[i].length<min)
{
min=st[i].length;
k=i;
}
st[k].label=permanent;
}
while(k!=s);
int * path = new int [n];
//Printing the path
cout<<"\nPATH::/n";
i=0;k=s;
do
{
cout<<k <<" --> ";
path[i++]=k;
k=st[k].predecessor;
}
while(k>=0);
cout<<endl;
}
int main()
{
int n,s,t;
cout<<"Enter the number of vertices"<<"\n";
cin>>n;
cout<<"Enter the source vertex"<<"\n";
cin>>s;
cout<<"Enter the destination"<<"\n";
cin>>t;
int ** dist = new int * [n];
for(int I = 0 ; I<n ; I++)
{
dist[I] = new int [n];
}
for(int i=0;i<n;i++)
{
cout<<"Enter the weights for row"<<i<<"\n";
for(int j=0;j<n;j++)
{
cin>>dist[i][j];
}
}
shortest_path(s,t,n,dist);
return 0;
}