forked from Parrva-Shah/Maze_Pathfinding_Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS_Solver.cpp
More file actions
86 lines (68 loc) · 2.55 KB
/
Copy pathBFS_Solver.cpp
File metadata and controls
86 lines (68 loc) · 2.55 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
#include "BFS_Solver.h"
#include <iostream>
BFS_Solver::BFS_Solver(const Maze& maze)
: Solver(maze, 'B')
{
int rows = maze.getRows();
int cols = maze.getCols();
visited.assign(rows, std::vector<bool>(cols, false));//2D vector<bool> functioning as a boolean matrix.
// parent is in base
q.push(start);//BFS requires a queue for level-by-level exploration
visited[start.first][start.second] = true;// start and goal are stored as pair<int,int> representing grid coordinates.
// Start the algorithm's timer
m_clock.restart();
}
void BFS_Solver::step() {
if (currentState == State::TRACING_PATH) {
// Count this node as part of the final path
m_pathLength++;
if (tracePos == start) {
currentState = State::DONE;// currentState is an enum that tracks the solver's phase
return;
}
if (grid[tracePos.first][tracePos.second] != 'E') {
grid[tracePos.first][tracePos.second] = 'X';
}
tracePos = parent[tracePos.first][tracePos.second];
return;
}
if (currentState != State::SEARCHING) return;
// No more nodes to explore means path not found
if (q.empty()) {
currentState = State::DONE;
found = false;
// Stop the clock if the search fails
m_timeTaken = m_clock.getElapsedTime();
return;
}
// Process next cell in the BFS queue
auto [r, c] = q.front();
q.pop();
// We are officially processing this node (pulling it from the queue)
m_nodesExplored++;
// Color the cell when we *process* it, not when we add it
if (grid[r][c] == ' ') {
grid[r][c] = symbol;
}
// If we popped the goal, switch to tracing
// (More efficient to check when adding, but this is fine)
if (r == goal.first && c == goal.second) {
found = true;
currentState = State::TRACING_PATH;
tracePos = goal;
// Stop the clock on success
m_timeTaken = m_clock.getElapsedTime();
return;
}
// Explore all four directions
for (auto [dr, dc] : directions) {
int nr = r + dr, nc = c + dc;
if (!isInside(grid, nr, nc)) continue;
char cell = grid[nr][nc];
if (cell == '#' || visited[nr][nc]) continue;
visited[nr][nc] = true;
parent[nr][nc] = {r, c};
// We only push to queue here. We *don't* color.
q.push({nr, nc});
}
}