-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcycle.cpp
73 lines (71 loc) · 1.37 KB
/
cycle.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
#include <iostream>
using namespace std;
int i,j;
int stepcount = 0;
bool dfs(int adj[][10],int r, int v)
{
int visited[r];
for (i = 0; i < r; i++)
{
stepcount++;
visited[i] = 0;
stepcount++;
}
visited[v] = 1;stepcount++;
int Stack[20],top = -1;stepcount++;
top++;stepcount++;
Stack[top] = v;stepcount++;
while (top != -1)
{
stepcount+=1;
int w = Stack[top--];stepcount++;
cout << w << " ";stepcount++;
int u = 0;stepcount++;
while (u < r)
{
stepcount++;
if (visited[u] == 1 && adj[w][u] == 1)
return true;
stepcount++;
stepcount++;
if (adj[w][u] == 1 && visited[u] == 0)
{
stepcount++;
visited[u] = 1;stepcount++;
Stack[++top] = u;stepcount++;
}
u++;stepcount++;
//stepcount++;
}
stepcount++;
}
return false;
}
int main()
{
int mat[10][10],r,src;
cout << "\nEnter the number of vertices in the graph: ";stepcount++;
cin >> r;stepcount++;
cout << "\nEnter the adjacency matrix: \n";stepcount++;
for (i = 0; i < r; i++)
{
stepcount++;
for (j = 0; j < r; j++)
{
stepcount++;
cin >> mat[i][j];
stepcount++;
}
stepcount++;
}
stepcount++;
cout << "\nEnter the source vertex: ";stepcount++;
cin >> src;stepcount++;
stepcount++;
bool k= dfs(mat,r,src);
if (k)
cout << "\nCycle exists!";
stepcount++;
cout << "\nThe number of steps for "<<r<<"-vertex graph is: " << ++stepcount<<endl;
return 0;
}