-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.cpp
More file actions
64 lines (54 loc) · 988 Bytes
/
dfs.cpp
File metadata and controls
64 lines (54 loc) · 988 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
///Implement Depth-First Search in a graph
/// MADE BY CHETAN KHANNA
#include <bits/stdc++.h>
using namespace std;
vector <int> adj[10];
bool visited[10];
void addEdge(int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void dfs(int s)
{
visited[s] = true;
cout<<s<<" ";
for(int i = 0; i < adj[s].size(); ++i)
{
if(visited[adj[s][i]] == false)
{
dfs(adj[s][i]);
}
}
}
void initialize()
{
for(int i = 0; i < 10; ++i)
visited[i] = false;
}
int main()
{
int nodes, edges, x, y;
cin >> nodes;
cin >> edges;
for(int i = 0; i < edges; ++i)
{
cin >> x >> y;
addEdge(x,y); //Edge from vertex x to vertex y
}
int s = 0;
cout<<"\n\nDFS : ";
dfs(s);
return 0;
}
/*
addEdge(0, 1);
addEdge(0, 4);
addEdge(1, 2);
addEdge(1, 3);
addEdge(1, 4);
addEdge(2, 3);
addEdge(3, 4);
initialize();
*/
/// DFS : 0 1 2 3 4