forked from bhonesh1998/Data-Structures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.cpp
More file actions
98 lines (83 loc) · 1.95 KB
/
dfs.cpp
File metadata and controls
98 lines (83 loc) · 1.95 KB
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
/*
***********************************************************
***********************************************************
NAME-BHONESH CHAWLA
REGNO-20164017
BATCH-CS-1
CONTACT-+918619127663
EMAIL-rajachawla778@gmail.com
***********************************************************
***********************************************************
*/
// implementation of depth first search using adjacency matrix
#include <bits/stdc++.h>
#define sf scanf
#define pf printf
#define z long long int
using namespace std;
int g[100][100];
bool state[100]={false};
int v;
//-------------------------------------------------------------------------------------------------
void sol(int ver)
{
stack<int> st;
st.push(ver);
while(!st.empty())
{
int s=st.top();
st.pop();
if(!state[s])
{
state[s]=true;
pf("%d ",s);
}
for(int i=0;i<v;i++)
{
if( (g[s][i]==1) && (state[i]==false) )
st.push(i);
}
}
}
//-------------------------------------------------------------------------------------------------
int main()
{
int i,j,p;
pf("enter number of vertices \n");
sf("%d",&v);
for(i=0;i<v;i++)
{
for(j=0;j<v;j++)
g[i][j]=0;
}
int noe = (v*(v-1) )/2;
int a,b;
for(i=0;i<noe;i++)
{
pf("enter 2 vertices for an edge\n (-1 -1 to break) ");
sf("%d %d",&a,&b);
if(a==-1 && b==-1)
break;
g[a][b]=1;
g[b][a]=1;
}
pf("graph is \n");
for(i=0;i<v;i++)
{
for(j=0;j<v;j++)
{
pf("%d ",g[i][j]);
}
pf("\n");
}
pf("after dfs nodes are :- \n");
for(i=0;i<v;i++)
{
if(state[i]==false)
{
sol(i);
}
}
return 0;
}
//-------------------------------------------------------------------------------------------------