-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDFS_Solver.cpp
More file actions
91 lines (71 loc) · 2.82 KB
/
Copy pathDFS_Solver.cpp
File metadata and controls
91 lines (71 loc) · 2.82 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
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
#include "DFS_Solver.h"
#include <iostream>
DFS_Solver::DFS_Solver(const Maze& maze)
: Solver(maze, 'D')
{
int R = maze.getRows();
int C = maze.getCols();
visited.assign(R, std::vector<bool>(C, false));
// 'parent' is initialized in base Solver
stk.push(start);//stk is a stack<pair<int,int>> used to implement DFS iteratively.
// Start the algorithm's timer
m_clock.restart();
}
void DFS_Solver::step() {
if (currentState == State::TRACING_PATH) {
// Count this node as part of the final path
m_pathLength++;
if (tracePos == start) {
currentState = State::DONE;
return;
}
// Use 'X' for the final path
if (grid[tracePos.first][tracePos.second] != 'E') {// grid is a 2D vector<char> representing the maze layout
grid[tracePos.first][tracePos.second] = 'X';
}
tracePos = parent[tracePos.first][tracePos.second];
return;
}
if (currentState != State::SEARCHING) return;
// Loop until we find a new node to process or the stack is empty
while (!stk.empty()) {
auto [r, c] = stk.top();
stk.pop();
// If already visited, pop and continue the loop (do not return!)
if (visited[r][c]) {
continue;
}
// This is the first time we are officially processing this node
m_nodesExplored++;
visited[r][c] = true;
if (grid[r][c] == ' ') grid[r][c] = symbol;
// If we've reached the goal cell, switch to TRACING
if (std::make_pair(r,c) == goal) {
found = true;
currentState = State::TRACING_PATH;
tracePos = goal; // Start tracing from the goal
// Stop the clock on success
m_timeTaken = m_clock.getElapsedTime();
return; // Exit step
}
// Push unvisited neighbors
for (int i = 3; i >= 0; --i) { // Iterating backwards to explore in a consistent order
int nr = r + directions[i].first;
int nc = c + directions[i].second;
if (!isInside(grid, nr, nc)) continue;
if (grid[nr][nc] == '#') continue;
if (visited[nr][nc]) continue;
parent[nr][nc] = {r, c};
stk.push({nr, nc});
}
// We processed one valid, unvisited node. Exit step for visualization.
return;
}
// This part is reached only if the while loop exits (stack is empty)
if (currentState == State::SEARCHING) {
currentState = State::DONE;
found = false;
// Stop the clock if the search fails
m_timeTaken = m_clock.getElapsedTime();
}
}