-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcycles_tarjan_c_implementation.cpp
135 lines (116 loc) · 2.23 KB
/
cycles_tarjan_c_implementation.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
#include<iostream>
#include <cstdio>
#include<list>
#include<stack>
using namespace std;
int** g_adj; // adjacency matrix
int g_numV; // number of vertices
stack<int>current_stack;
stack<int>marked_stack;
bool* marked;
int s;
// initialize the structures
void initialize(int verts)
{
g_numV = verts;
g_adj = new int* [g_numV];
marked = new bool [g_numV];
for(int i=0;i<g_numV;i++)
{
marked[i]=false;
g_adj[i] = new int [g_numV];
for(int j=0;j<g_numV;j++)
{
g_adj[i][j] = 0;
}
}
}
// populate adjacency matrix
void createAdjacencyMatrix(FILE* fp) {
for(int i=0;i<g_numV;i++) {
for(int j=0;j<g_numV;j++) {
// no loops allowed!
fscanf(fp, "%d", &(g_adj[i][j]));
if(i == j) {
g_adj[i][j] = 0;
}
}
}
}
void print_current_stack()
{
for(stack<int>dump=current_stack;!dump.empty();dump.pop())
{
cout<<dump.top()<< " ";
//mylist.pop();
}
}
// DFS algo!
bool visitVertex(int v)
{
bool flag =false;
current_stack.push(v);
marked_stack.push(v);
marked[v]=true;
for(int i=0;i<g_numV;i++)
{
if(!g_adj[v][i])
{
continue;
}
if (i<s)
return 0;
else if(i==v)
{
print_current_stack();
flag=true;
}
else if(!marked[i])
{
flag= (flag | visitVertex(i));
}
}
if (flag==true)
{
while(marked_stack.top()!=v)
{
int x=marked_stack.top();
marked[x]=false;
marked_stack.pop();
}
marked_stack.pop();
marked[v]=false;
}
current_stack.pop();
return flag;
}
// cycle-finder!
void findCycles()
{
int u;
for( s=0;s<g_numV;s++)
{
visitVertex(s);
while(!marked_stack.empty())
{
u=marked_stack.top();
marked[u]=false;
marked_stack.pop();
}
}
}
int main() {
FILE* fp = fopen("example.txt", "r");
if(fp == NULL) {
printf( "Failed to open the file for reading!\n");
return 1;
}
int numVerts;
fscanf(fp, "%d enter the number of vertices", &numVerts);
initialize(numVerts);
createAdjacencyMatrix(fp);
fclose(fp);
findCycles();
//finalize();
return 0;
}