-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDFS.cpp
More file actions
41 lines (31 loc) · 656 Bytes
/
DFS.cpp
File metadata and controls
41 lines (31 loc) · 656 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
#include <bits/stdc++.h>
using namespace std;
class Graph {
public:
map<int, bool> visited;
map<int, list<int>> adj;
void addEdge(int v, int w);
void DFS(int v);
};
void Graph::addEdge(int v, int w) {
adj[v].push_back(w);
}
void Graph::DFS(int v) {
visited[v] = true;
cout << v << " ";
for (int neighbor : adj[v])
if (!visited[neighbor])
DFS(neighbor);
}
int main() {
Graph g;
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "DFS Traversal (starting from vertex 2)\n";
g.DFS(2);
return 0;
}