-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph_DFS.cpp
52 lines (43 loc) · 829 Bytes
/
Graph_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
#include<iostream>
#include <list>
#include<vector>
using namespace std;
int v;
vector<int> *g;
void constructGraph()
{
g=new vector<int>[v];
}
void addEdge(int v, int w)
{
g[v].push_back(w);
}
void DFSUtil(int n, bool* &visited)
{
visited[n] = true;
cout << n << " ";
for(vector<int>::iterator i = g[n].begin(); i!=g[n].end(); i++)
if(!visited[*i])
DFSUtil(*i, visited);
}
void DFS(int n)
{
bool *visited=new bool[v];
for(int i = 0; i < v; i++)
visited[i] = false;
DFSUtil(n, visited);
}
int main()
{
v=4;
constructGraph();
addEdge(0, 1);
addEdge(0, 2);
addEdge(1, 2);
addEdge(2, 0);
addEdge(2, 3);
addEdge(3, 3);
cout << "Following is Depth First Traversal (starting from vertex 2) \n";
DFS(2);
return 0;
}