Skip to content

Commit ea481a2

Browse files
authored
Create Detect cycle in a graph
1 parent d071a92 commit ea481a2

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Detect cycle in a graph

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#include <iostream>
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
#define V 4
5+
6+
void dfs(int mat[V][V] , int u ,int v)
7+
{
8+
for(int i = 0;i<V;i++)
9+
{
10+
if(mat[v][i] == 1)
11+
{
12+
if(i==u)
13+
{
14+
mat[v][u]= 0 ;
15+
//return;
16+
}
17+
else
18+
{
19+
dfs(mat,u,i);
20+
}
21+
}
22+
}
23+
}
24+
25+
void print(int mat[V][V])
26+
{
27+
for(int i=0;i<V;i++)
28+
{
29+
for(int j=0;j<V;j++)
30+
{
31+
cout<<mat[i][j]<<" ";
32+
}
33+
cout<<endl;
34+
}
35+
}
36+
37+
38+
void cycle(int mat[V][V])
39+
{
40+
for(int i=0;i<V;i++)
41+
{
42+
43+
for(int j=0;j<V;j++)
44+
{
45+
if(mat[i][j] == 1)
46+
{
47+
dfs(mat,i,j);
48+
}
49+
}
50+
}
51+
print(mat);
52+
}
53+
54+
int main()
55+
{
56+
57+
int mat[V][V] = {{0, 0, 1, 1},
58+
{1, 0, 0, 0},
59+
{1, 1, 0, 0},
60+
{0, 0, 0, 1} } ;
61+
62+
for(int i=0;i<V;i++)
63+
{
64+
if(mat[i][i]==1)
65+
{
66+
mat[i][i] = 0;
67+
}
68+
}
69+
cycle(mat);
70+
71+
return 0;
72+
}

0 commit comments

Comments
 (0)