-
Notifications
You must be signed in to change notification settings - Fork 0
/
DFS.cpp
51 lines (46 loc) · 857 Bytes
/
DFS.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
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
const int INF= INT_MAX;
stack<int> S;
int V;
int E;
bool visited[100];
vector<int>adj[100];
int main()
{
cin>>V>>E;
for(int i=0;i<E;i++)
{
int u,v;
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
for(int i=0;i<V;i++)
visited[i]=false;
int s=0;
visited[s]=true;
S.push(s);
while(!S.empty())
{
int j=S.top();
S.pop();
cout<<j<<" ";
int n=adj[j].size();
for(int i=0;i<n;i++)
{
int h=adj[j][i];
if(visited[h]==false)
{
visited[h]=true;
S.push(h);
// cout<<h;
}
}
}
///cout<<endl;
// for(int i=0;i<V;i++)
// cout<<d[i]<<" ";
}