-
Notifications
You must be signed in to change notification settings - Fork 10
/
StronglyConnectedComponentInGraph.cpp
162 lines (161 loc) · 2.95 KB
/
StronglyConnectedComponentInGraph.cpp
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/*
* C++ Program to Find Strongly Connected Components in Graphs
*/
struct node_info
{
int no;
int lv_time, st_time;
}*q = NULL;
struct node
{
node_info *pt;
node *next;
}*top = NULL, *p = NULL, *np = NULL;
struct node1
{
node1 *link;
node_info *pt1;
}*head = NULL, *m = NULL, *n = NULL, *np1 = NULL;
int c = 0;
void push(node_info *ptr)
{
np = new node;
np->pt = ptr;
np->next = NULL;
if (top == NULL)
{
top = np;
}
else
{
np->next = top;
top = np;
}
}
node_info *pop()
{
if (top == NULL)
{
cout<<"underflow\n";
}
else
{
p = top;
top = top->next;
return(p->pt);
delete(p);
}
}
void store(node_info *ptr1)
{
np1 = new node1;
np1->pt1 = ptr1;
np1->link = NULL;
if (c == 0)
{
head = np1;
m = head;
m->link = NULL;
c++;
}
else
{
m = head;
np1->link = m;
head = np1;
}
}
void remove(int x)
{
m = head;
if ((m->pt1)->no == x)
{
head = head->link;
delete(m);
}
else
{
while ((m->pt1)->no != x && m->link != NULL)
{
n = m;
m = m->link;
}
if ((m->pt1)->no == x)
{
n->link = m->link;
delete(m);
}
else if (m->link == NULL)
{
cout<<"error\n";
}
}
}
void topo(int *v, int am[][8], int i)
{
q = new node_info;
q->no = i;
q->st_time = c;
push(q);
v[i] = 1;
for (int j = 0; j < 8; j++)
{
if (am[i][j] == 0 || (am[i][j] == 1 && v[j] == 1))
continue;
else if (am[i][j] == 1 && v[j] == 0)
{
c++;
topo(v,am,j);
}
}
c++;
q = pop();
q->lv_time = c;
store(q);
return;
}
void topo1(int *v, int am[][8], int i)
{
v[i] = 1;
remove(i);
cout<<i<<endl;
for (int j = 0; j < 8; j++)
{
if (am[i][j] == 0 || (am[i][j] == 1 && v[j] == 1))
{
continue;
}
else if (am[i][j] == 1 && v[j] == 0)
{
topo1(v,am,j);
}
}
return;
}
int main()
{
int v[8], am[8][8], amt[8][8];
for (int i = 0; i < 8; i++)
v[i] = 0;
for (int i = 0; i < 8; i++)
{
cout<<"enter the values for adjacency matrix row:"<<i + 1<<endl;
for (int j = 0; j < 8; j++)
{
cin>>am[i][j];
}
}
topo(v, am, 0);
for (int i = 0; i < 8; i++)
{
v[i] = 0;
for (int j = 0; j < 8; j++)
amt[j][i] = am[i][j];
}
while (head != NULL)
{
cout<<"Strongly Connected Components:\n";
topo1(v, amt, (head->pt1)->no);
}
getch();
}