forked from aryasoni98/HacktoberfestPR2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdfs.cpp
39 lines (30 loc) · 694 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
#include "bits/stdc++.h"
using namespace std;
int n; //n -> number of nodes
queue<int> ans; //queue to print the answer
vector<bool> visited;
vector<vector<int> > adjList;
void dfs(int u){
if(visited[u]) return; //if it was previously visited, return
visited[u] = true;
for(int i = 0; i < adjList[u].size(); i++){
int v = adjList[u][i];
dfs(v);
}
ans.push(u);
}
int main(){
int u, v, start;
cin >> n >> start;
adjList.resize(n);
visited.resize(n);
while(cin >> u >> v){
adjList[u].push_back(v);
}
dfs(start);
while(!ans.empty()){
cout << ans.front() << '\n';
ans.pop();
}
return 0;
}