forked from skjha1/Data-Structure-Algorithm-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06 BreadthFirstSearchUsingSTLQueue.cpp
83 lines (68 loc) · 2.12 KB
/
06 BreadthFirstSearchUsingSTLQueue.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
#include <iostream>
#include <stack>
using namespace std;
// Based on Lecture
void DFS(int u, int A[][8], int n) {
// Initialize visit tracking array and stack
int visited[8] {0};
stack<int> stk;
stk.emplace(u);
// Visit start vertex u
cout << u << ", " << flush;
visited[u] = 1; // Visited vertex u
// Initial Adjacent vertex
int v = 0;
while (!stk.empty()){
while (v < n){
if (A[u][v] == 1 && visited[v] == 0){
stk.push(u); // Suspend exploring current vertex u
u = v; // Update current vertex as the next adjacent vertex
// Visit current vertex u
cout << u << ", " << flush;
visited[u] = 1;
v = -1; // Increment will make this 0
}
v++;
}
v = u; // Can set v = 0 but setting v = u is better
u = stk.top(); // Return to previous suspended vertex
stk.pop();
}
}
// Simpler and adds elements to stack from end
void dfs(int u, int A[][8], int n){
int visited[8] {0};
stack<int> stk;
stk.emplace(u);
while (!stk.empty()){
u = stk.top();
stk.pop();
if (visited[u] != 1){
cout << u << ", " << flush;
visited[u] = 1;
for (int v=n-1; v>=0; v--){
if (A[u][v] == 1 && visited[v] == 0){
stk.emplace(v);
}
}
}
}
}
int main (){
int A[8][8] = {{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 1, 1, 0, 0, 0},
{0, 1, 0, 1, 0, 0, 0, 0},
{0, 1, 1, 0, 1, 1, 0, 0},
{0, 1, 0, 1, 0, 1, 0, 0},
{0, 0, 0, 1, 1, 0, 1, 1},
{0, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0}};
int u = 5;
cout << "DFS Vertex: " << u << " -> " << flush;
DFS(u, A, 8);
cout << endl;
cout << "dfs Vertex: " << u << " -> " << flush;
dfs(u, A, 8);
cout << endl;
return 0;
}