-
Notifications
You must be signed in to change notification settings - Fork 0
/
dfs.cpp
56 lines (37 loc) · 1.03 KB
/
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
52
53
54
55
56
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
void dfs(vector< vector<int> > adjacencyList, int startNode){
vector<bool> isVisited(adjacencyList.size(), false);
stack<int> order;
order.push(startNode);
int temp;
while(!order.empty()){
temp = order.top();
cout << temp << endl;
order.pop();
isVisited[temp] = true;
for(int i = 0; i < adjacencyList[temp].size(); i++){
if(!isVisited[adjacencyList[temp][i]]) order.push(adjacencyList[temp][i]);
}
}
}
int main(){
vector< vector<int> > nodes;
nodes.push_back(vector<int>());
nodes.push_back(vector<int>());
nodes.push_back(vector<int>());
nodes.push_back(vector<int>());
nodes.push_back(vector<int>());
nodes[0].push_back(1);
nodes[1].push_back(0);
nodes[1].push_back(2);
nodes[2].push_back(1);
nodes[3].push_back(2);
nodes[2].push_back(3);
nodes[4].push_back(2);
nodes[2].push_back(4);
dfs(nodes,3);
return 0;
}