-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.cpp
More file actions
55 lines (52 loc) · 1.19 KB
/
DFS.cpp
File metadata and controls
55 lines (52 loc) · 1.19 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
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> adj;
vector<bool> visited;
void dfs(int from) {
cout << endl << "--dfs(" << from << ") is called--" << endl;
cout << " so visited " << from <<" will be 'true'" << endl;
visited[from] = true;
for (size_t i = 0; i < adj[from].size(); ++i) {
int to = adj[from][i];
cout << " from : "<<from<<"/ to : " << to << endl;
if (!visited[to]) {
cout << " dfs(" << to << ") is called" << endl;
dfs(to);
}
}
}
void dfsAll() {
visited = vector<bool>(adj.size(), false);
for (size_t i = 0; i < adj.size(); ++i) {
if (!visited[i]) {
cout << endl << "-dfsAll(" << i << ") is called-" << endl;
dfs(i);
}
else {
cout << "node " << i << " is already visited" << endl;
}
}
}
void showAdj(vector<vector<int>> adjacent) {
for (size_t i = 0; i < adjacent.size(); ++i) {
for (size_t j = 0; j < adj[i].size(); ++j) {
if (adjacent[i][j] != NULL)
{
cout << i << " -> " << adjacent[i][j] << endl;
}
}
}
}
int main() {
adj.resize(7);
visited.resize(7);
adj[0].push_back(1);
adj[0].push_back(2);
adj[1].push_back(3);
adj[1].push_back(4);
adj[5].push_back(6);
showAdj(adj);
dfsAll();
return 0;
}