1
+ #include < iostream>
2
+ #include < stack>
3
+
4
+ using namespace std ;
5
+
6
+ // Based on Lecture
7
+ void DFS (int u, int A[][8 ], int n) {
8
+ // Initialize visit tracking array and stack
9
+ int visited[8 ] {0 };
10
+ stack<int > stk;
11
+ stk.emplace (u);
12
+
13
+ // Visit start vertex u
14
+ cout << u << " , " << flush;
15
+ visited[u] = 1 ; // Visited vertex u
16
+
17
+ // Initial Adjacent vertex
18
+ int v = 0 ;
19
+
20
+ while (!stk.empty ()){
21
+ while (v < n){
22
+ if (A[u][v] == 1 && visited[v] == 0 ){
23
+ stk.push (u); // Suspend exploring current vertex u
24
+ u = v; // Update current vertex as the next adjacent vertex
25
+
26
+ // Visit current vertex u
27
+ cout << u << " , " << flush;
28
+ visited[u] = 1 ;
29
+ v = -1 ; // Increment will make this 0
30
+ }
31
+ v++;
32
+ }
33
+ v = u; // Can set v = 0 but setting v = u is better
34
+ u = stk.top (); // Return to previous suspended vertex
35
+ stk.pop ();
36
+ }
37
+ }
38
+
39
+ // Simpler and adds elements to stack from end
40
+ void dfs (int u, int A[][8 ], int n){
41
+ int visited[8 ] {0 };
42
+ stack<int > stk;
43
+ stk.emplace (u);
44
+
45
+ while (!stk.empty ()){
46
+ u = stk.top ();
47
+ stk.pop ();
48
+
49
+ if (visited[u] != 1 ){
50
+ cout << u << " , " << flush;
51
+ visited[u] = 1 ;
52
+
53
+ for (int v=n-1 ; v>=0 ; v--){
54
+ if (A[u][v] == 1 && visited[v] == 0 ){
55
+ stk.emplace (v);
56
+ }
57
+ }
58
+ }
59
+ }
60
+ }
61
+
62
+ int main (){
63
+
64
+ int A[8 ][8 ] = {{0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
65
+ {0 , 0 , 1 , 1 , 1 , 0 , 0 , 0 },
66
+ {0 , 1 , 0 , 1 , 0 , 0 , 0 , 0 },
67
+ {0 , 1 , 1 , 0 , 1 , 1 , 0 , 0 },
68
+ {0 , 1 , 0 , 1 , 0 , 1 , 0 , 0 },
69
+ {0 , 0 , 0 , 1 , 1 , 0 , 1 , 1 },
70
+ {0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 },
71
+ {0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 }};
72
+
73
+ int u = 5 ;
74
+ cout << " DFS Vertex: " << u << " -> " << flush;
75
+ DFS (u, A, 8 );
76
+ cout << endl;
77
+
78
+ cout << " dfs Vertex: " << u << " -> " << flush;
79
+ dfs (u, A, 8 );
80
+ cout << endl;
81
+
82
+ return 0 ;
83
+ }
0 commit comments