-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFS.cpp
66 lines (57 loc) · 1.29 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
57
58
59
60
61
62
63
64
65
/*
Graph:
0
/ \
1 2
/ \
3 4
\
5
Adjacency List:
0 -> 1 2
1 -> 0 3 4
2 -> 0
3 -> 1
4 -> 1 5
5 -> 4
0 to 2 --->Traverse
2 to 0 --->Backtrack
0 to 1 --->Traverse
1 to 4 --->Traverse
4 to 5 --->Traverse
5 to 4 --->Backtrack
4 to 1 --->Backtrack
1 to 3 --->Traverse
*/
#include <bits/stdc++.h>
using namespace std;
void DFS(int start, vector<vector<int>>& adj_list){
stack<int> Vnodes;
vector<bool> visited(adj_list.size(), false);
Vnodes.push(start);
visited[start] = true;
while(!Vnodes.empty()){
int current = Vnodes.top();
cout<<current<<" ";
Vnodes.pop();
for(int neighbour: adj_list[current]){
if(!visited[neighbour]){
visited[neighbour] = true;
Vnodes.push(neighbour);
}
}
}
}
int main() {
vector<vector<int>> graph = {
{1, 2}, // Neighbors of vertex 0 -> graph[0]
{0, 3, 4}, // Neighbors of vertex 1 -> graph[1]
{0}, // Neighbors of vertex 2 -> graph[2]
{1}, // Neighbors of vertex 3 -> graph[3]
{1, 5}, // Neighbors of vertex 4 -> graph[4]
{4} // Neighbors of vertex 5 -> graph[5]
};
cout << "DFS Traversal: "; // DFS Traversal: 0 2 1 4 5 3
DFS(0, graph);
return 0;
}