-
Notifications
You must be signed in to change notification settings - Fork 0
/
DFS.cpp
43 lines (37 loc) · 823 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
#include<bits/stdc++.h>
using namespace std;
int visited[1000];
int level[1000];
void dfsGraph(vector <int> adj[], int s){
int v,i;
stack <int> st;
st.push(s);
visited[s] = 1;
while (!st.empty()){
v = st.top();
cout << v <<" ";
st.pop();
for(i=0; i<adj[v].size(); i++){
if(visited[adj[v][i]] == 0)
{
st.push(adj[v][i]);
visited[adj[v][i]] = 1;
}
}
}
}
int main() {
// your code goes here
int vertices, edges, i, j, v_source, v_destination;
cin >> vertices;
cin >> edges;
vector <int> adj[vertices+1];
for(i=0; i<edges; i++){
cin >> v_source;
cin >> v_destination;
adj[v_source].push_back(v_destination); //if undirected graph hence adding to both adjacenct lists
adj[v_destination].push_back(v_source);
}
dfsGraph(adj, 1);
return 0;
}