-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlongestpath_on_dag_geek.c
133 lines (109 loc) · 2.37 KB
/
longestpath_on_dag_geek.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
123
124
125
126
127
128
129
130
131
132
133
#include <stdio.h>
#define MAX 1000
#define INF 99999
int graph[MAX][MAX];
int num;
int stackptr = -1;
int stack[MAX];
int distance[MAX];
int visited[MAX];
int peek()
{
return stack[stackptr];
}
int Push(int element)
{
if(IsStackFull())
return;
else {
stackptr += 1;
stack[stackptr] = element;
}
}
int Pop(void)
{
if(IsStackEmpty())
return -1;
else {
int element;
element = stack[stackptr];
stackptr -= 1;
return element;
}
}
int IsStackEmpty(void)
{
if (stackptr == -1)
return 1;
else
return 0;
}
int IsStackFull(void)
{
if (stackptr == MAX-1)
return 1;
else
return 0;
}
void DoTopologicalSortOnGraph(int startnode)
{
int adj;
for(adj = 0; adj < num; adj++) {
if (graph[startnode][adj] != INF && !visited[adj]) {
visited[adj] = 1;
DoTopologicalSortOnGraph(adj);
}
}
/* Done exploring all children of startnode */
Push(startnode);
}
void UpdateDistances(int source)
{
int k;
int adj;
int node = Pop();
/* Keep popping till we find the source */
while(source != node) {
node = Pop();
}
Push(node);
while(!IsStackEmpty()) {
node = Pop();
for(adj = 0; adj < num; adj++) {
if (graph[node][adj] == INF)
continue;
if (distance[adj] == INF) {
distance[adj] = distance[node] + graph[node][adj];
} else if (distance[adj] < graph[node][adj] + distance[node] ) {
distance[adj] = graph[node][adj] + distance[node];
}
}
}
}
int main()
{
int r;
int c;
int k;
printf("Welcome to find Longest path on DAG..uisng toposort..\n");
printf("Enter number of nodes..\n");
scanf("%d", &num);
for(r=0; r< num; r++) {
for(c=0; c< num; c++) {
scanf("%d", &graph[r][c]);
}
}
for(k=0; k< num; k++)
visited[k] = 0;
int startnode = 0;
visited[startnode] = 1;
DoTopologicalSortOnGraph(startnode);
printf("Topological sorting Done..\n");
for(k=0; k < num; k++)
distance[k] = INF;
int source = 1;
distance[source] = 0;
UpdateDistances(source);
for(k=0; k < num; k++)
printf("Distance from source %d to %d = [%d]\n", source, k, distance[k]);
}