-
Notifications
You must be signed in to change notification settings - Fork 207
/
Copy pathDFS.cpp
64 lines (53 loc) · 1.2 KB
/
DFS.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
58
59
60
61
62
63
64
#include<bits/stdc++.h>
using namespace std;
#define N 100
int visited[N];
void dfs_iterative(vector<int> graph[], int node){
stack<int> stack_dfs;
stack_dfs.push(node);
visited[node] = 1;
int cur_node;
while(!stack_dfs.empty()){
cur_node = stack_dfs.top();
stack_dfs.pop();
cout<<cur_node<<" ";
for(int i = 0; i<graph[cur_node].size(); i++){
if(visited[graph[cur_node][i]] == 0){
visited[graph[cur_node][i]] = 1;
stack_dfs.push(graph[cur_node][i]);
}
}
}
}
void dfs(vector<int> graph[], int node) {
if(visited[node] == 1)
return;
// Else
visited[node]=1;
cout<<node<<" ";
for(int i=0;i<graph[node].size();i++) {
dfs(graph, graph[node][i]);
}
}
void initialize() {
for(int i=1;i<=5;i++)
visited[i]=0;
}
int main() {
// Making a graph(number of nodes = 5) using adjacency list
vector<int> graph[6];
graph[1].push_back(2);
graph[1].push_back(4);
graph[2].push_back(1);
graph[2].push_back(3);
graph[2].push_back(5);
graph[3].push_back(2);
graph[3].push_back(5);
graph[4].push_back(1);
graph[5].push_back(2);
graph[5].push_back(3);
// Initially no node is visited
initialize();
dfs(graph,1);
return 0;
}