File tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change 1+
2+ #include < iostream>
3+ #include < list>
4+ using namespace std ;
5+
6+
7+ class Graph
8+ {
9+ int V;
10+
11+
12+ list<int > *adj;
13+
14+ void DFSUtil (int v, bool visited[]);
15+ public:
16+ Graph (int V);
17+
18+
19+ void addEdge (int v, int w);
20+
21+
22+ void DFS (int v);
23+ };
24+
25+ Graph::Graph (int V)
26+ {
27+ this ->V = V;
28+ adj = new list<int >[V];
29+ }
30+
31+ void Graph::addEdge (int v, int w)
32+ {
33+ adj[v].push_back (w);
34+ }
35+
36+ void Graph::DFSUtil (int v, bool visited[])
37+ {
38+
39+ visited[v] = true ;
40+ cout << v << " " ;
41+
42+
43+ list<int >::iterator i;
44+ for (i = adj[v].begin (); i != adj[v].end (); ++i)
45+ if (!visited[*i])
46+ DFSUtil (*i, visited);
47+ }
48+
49+
50+ void Graph::DFS (int v)
51+ {
52+
53+ bool *visited = new bool [V];
54+ for (int i = 0 ; i < V; i++)
55+ visited[i] = false ;
56+
57+
58+ DFSUtil (v, visited);
59+ }
60+
61+ int main ()
62+ {
63+
64+ Graph g (4 );
65+ g.addEdge (0 , 1 );
66+ g.addEdge (0 , 2 );
67+ g.addEdge (1 , 2 );
68+ g.addEdge (2 , 0 );
69+ g.addEdge (2 , 3 );
70+ g.addEdge (3 , 3 );
71+
72+ cout << " Depth First Traversal"
73+ " (starting from vertex 0) \n " ;
74+ g.DFS (0 );
75+
76+ return 0 ;
77+ }
You can’t perform that action at this time.
0 commit comments