-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.h
More file actions
36 lines (25 loc) · 672 Bytes
/
DFS.h
File metadata and controls
36 lines (25 loc) · 672 Bytes
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
//implementation of non-recursive dfs using stack on a graph with fixed size represented as adjacency matrix
#ifndef _DFS
#define _DFS
#include<stack>
#define SIZE 4
void DFS(int (&graph)[SIZE][SIZE], int start) {
bool checked[SIZE];
for (size_t i = 0; i < SIZE; ++i)
checked[i] = false;
std::stack<int> s;
//initiate the stack with the start elment
s.push(start);
checked[start] = true;
while (!s.empty()) {
int current = s.top();
checked[current] = true;
s.pop();
//push the ajacent nodes that are not yet checked
for (size_t i = 0; i < SIZE; ++i) {
if (!checked[i] && graph[current][i] != 0)
s.push(i);
}
}
}
#endif // !_DFS