-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq2.cpp
More file actions
48 lines (38 loc) · 878 Bytes
/
Copy pathq2.cpp
File metadata and controls
48 lines (38 loc) · 878 Bytes
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
#include <iostream>
#include <vector>
using namespace std;
class Graph {
public:
int V;
vector<vector<int>> adj;
Graph(int V) {
this->V = V;
adj.resize(V);
}
void addEdge(int u, int v) {
adj[u].push_back(v);
adj[v].push_back(u); // undirected
}
void dfsHelper(int node, vector<bool> &visited) {
visited[node] = true;
cout << node << " ";
for(int nbr : adj[node]) {
if(!visited[nbr])
dfsHelper(nbr, visited);
}
}
void DFS(int start) {
vector<bool> visited(V, false);
cout << "DFS Traversal: ";
dfsHelper(start, visited);
}
};
int main() {
Graph g(5);
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(1,3);
g.addEdge(2,4);
g.DFS(0);
return 0;
}