forked from TECHOUS/AlgoHeist
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.cpp
More file actions
48 lines (44 loc) · 1018 Bytes
/
DFS.cpp
File metadata and controls
48 lines (44 loc) · 1018 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
#include<bits/stdc++.h>
using namespace std;
//start the vertex numbering from 0 in the input
void dfs(vector<int>adj[], int source, bool visited[]){
if(visited[source]==false) {
visited[source] = true;
cout << source << "-> ";
for(int i=0;i<adj[source].size();i++) {
if(!visited[adj[source][i]])
dfs(adj,adj[source][i],visited);
}
}
}
int main(){
int e,v,u,w,source;
cout << "enter number of edges: ";
cin >> e;
cout << "enter number of vertices: ";
cin >> v;
cout << "tell the vertices between which there exist an edge\n";
vector<int> adj[v];
for (int i = 0; i < e; ++i)
{
cin >> u >> w;
adj[u].push_back(w);
adj[w].push_back(u);
}
cout << "enter the source node: ";
cin >> source;
cout << endl << "Adjacency list" << endl;
for (int i = 0; i < v; ++i)
{
cout << i << " -> ";
for (int j = 0; j < adj[i].size(); ++j)
{
cout<<adj[i][j]<<" -> ";
}
cout<<endl;
}
cout << endl;
bool visited[v];
memset(visited,false,sizeof(visited));
dfs(adj,source,visited);
}