-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdigraph_traversal.cpp
92 lines (80 loc) · 2.18 KB
/
digraph_traversal.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
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
#include <iostream>
#include <list>
#include <queue>
#include <vector>
using namespace std;
class Digraph {
public:
int vertexNum; // Number of vertices
vector<vector<bool>> adj; // Adjacency matrix presentation, unweighted directed graph
Digraph(int n) : vertexNum(n) {
adj.resize(n);
for (auto it = adj.begin(); it != adj.end(); it++) {
it->resize(n);
}
}
void BFS(); // Print in BFS order
void DFS(); // Print in DFS order
private:
void DFS_recursive(int& vertex, vector<bool>& visited);
};
void Digraph::BFS() {
queue<int> que;
vector<bool> visited(vertexNum, false);
for (int i = 0; i < vertexNum; i++) { // In case the graph is not connected
if (!visited[i]) {
que.push(i);
while (!que.empty()) {
int current = que.front();
que.pop();
if (!visited[current]) {
cout << current << " "; // Visit the vertex
visited[current] = true;
for (int j = 0; j < vertexNum; j++) {
if (adj[current][j] == true && !visited[j]) {
que.push(j);
}
}
}
}
}
}
}
void Digraph::DFS() {
vector<bool> visited(vertexNum, false);
for (int i = 0; i < vertexNum; i++) { // In case the graph is not connected
if (!visited[i]) {
DFS_recursive(i, visited);
}
}
}
void Digraph::DFS_recursive(int& current, vector<bool>& visited) {
cout << current << " "; // Visit the vertex
visited[current] = true;
for (int j = 0; j < vertexNum; j++) {
if (adj[current][j] && !visited[j]) {
DFS_recursive(j, visited);
}
}
}
int main() {
int n;
cin >> n;
Digraph g(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
bool temp;
cin >> temp;
g.adj[i][j] = temp;
}
}
cout << endl;
cout << "DFS: ";
g.DFS();
cout << endl;
cout << "BFS: ";
g.BFS();
cout << endl;
system("pause");
return 0;
}