forked from krish-ag/HacktoberFest22-Repo-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
code5.cpp
57 lines (50 loc) · 1.1 KB
/
code5.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
53
54
55
56
57
// Depth First search
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int inf = 1e9 + 7;
void add_edge(vector<int> vec[], int u, int v)
{
vec[u].push_back(v);
vec[v].push_back(u);
}
void dfs(vector<int> vec[], int source, vector<bool> &visited)
{
visited[source] = true;
cout << source << " ";
for (int i = 0; i < vec[source].size(); i++)
{
int adjacent = vec[source][i];
if (visited[adjacent] == false)
{
dfs(vec, adjacent, visited);
}
}
}
void dfs_rec(vector<int> vec[], int v)
{
vector<bool> visited(v, false);
for (int i = 0; i < v; i++)
{
if (visited[i] == false)
{
dfs(vec, i, visited);
}
}
}
int main()
{
int v;
v = 6;
vector<int> adj[v];
// adding edges now
add_edge(adj, 0, 1);
add_edge(adj, 0, 2);
add_edge(adj, 0, 3);
add_edge(adj, 1, 4);
add_edge(adj, 1, 5);
add_edge(adj, 2, 5);
cout << "DEPTH FIRST SEARCH: " << endl;
dfs_rec(adj, v);
return 0;
}