-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathDFS.cpp
More file actions
92 lines (68 loc) · 1.5 KB
/
DFS.cpp
File metadata and controls
92 lines (68 loc) · 1.5 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
We can peform multisorurce bfs also for the problems of type
1. there are k hospitals and n cities and they are connected so find closest hostila form each city
Add all hospitals as src and do bfs on unvisited nodes so ...
Time Complexity: O(V + E)
*/
#include<bits/stdc++.h>
#define LIM 3000
#define INF 1e5+3
using namespace std;
vector<int> adj[LIM];
bool visited[LIM];
void addEdge(int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void dfs_iterative(int src)
{
memset(visited,0,sizeof(visited));
stack<int> stck;
stck.push(src);
while(stck.size())
{
int u=stck.top();
stck.pop();
visited[u]=true;
cout<<u<<" ";
for(auto v:adj[u])
{
if(!visited[v])
stck.push(v);
}
}
memset(visited,0,sizeof(visited));
}
void dfs_recursive(int u)
{
if(visited[u])
return ;
visited[u]=true;
cout<<u<<" ";
for(int v : adj[u])
{
if(!visited[v])
dfs_recursive(v);
}
}
int main()
{
int V,i,src,u,v,wt;
cout<<"Enter number of vertices and edges: ";
cin>>V>>E;
for(i=0;i<E;i++)
{
cout<<i+1<<". Enter vertex name u and v: ";
cin>>u>>v;
addEdge(u,v);
}
cout<<"Enter source node for iterative dfs: ";
cin>>src;
cout<<"Iterative_DFS=> ";
dfs_iterative(0);
cout<<endl;
cout<<"Enter source node for recursive dfs: ";
cin>>src;
cout<<"Recursive_DFS=> ";
}