-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs_dfs.cpp
More file actions
77 lines (74 loc) · 1.79 KB
/
bfs_dfs.cpp
File metadata and controls
77 lines (74 loc) · 1.79 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
#include<bits/stdc++.h>
using namespace std;
bool visited[100];
void dfs(vector<int> graph[], int N, int src){
cout << src << " ";
visited[src] = true;
for(int adj_node : graph[src]){
if(!visited[adj_node]){
dfs(graph,N,adj_node);
}
}
}
void dfs_iter(vector<int> graph[], int N,int src){
stack<int> s;
vector<bool> visited(N,false);
s.push(src);
visited[src] = true;
while(!s.empty()){
int curr_node = s.top();
s.pop();
cout << curr_node << " ";
for(int adj_node : graph[curr_node]){
if(!visited[adj_node]){
s.push(adj_node);
visited[adj_node] = true;
}
}
}
cout << "\n";
}
void bfs(vector<int> graph[] ,int N, int src){
queue<int> q;
vector<bool> visited(N,false);
q.push(src);
visited[src] = true;
while(!q.empty()){
int curr_node = q.front();
q.pop();
cout << curr_node <<" ";
for(int adj_node:graph[curr_node]){
if(!visited[adj_node]){
q.push(adj_node);
visited[adj_node] = true;
}
}
}
cout <<"\n";
}
void print(vector<int> tree[],int N){
for(int i =0;i<N;i++){
cout << i <<" => ";
for(int adj_node : tree[i])
cout << adj_node << ",";
cout << "\n";
}
}
int main(){
int N,node;
cout << "Enter No of Nodes => \n";
cin >> N;
vector<int> graph[N];
for(int i=0;i<N;i++){
while(true){
cin >> node;
if(node == -1)
break;
graph[i].push_back(node);
}
}
print(graph,N);
dfs_iter(graph,N,0);
dfs(graph,N,0);
return 0;
}