Breadth-First Search Implementation for Maze Pathfinding
#include <iostream>
#include <queue>
#include <string>
using namespace std;
struct Position {
int row;
int col;
string route;
};
char mazeGrid[30][50];
char directionSymbols[] = {'D', 'L', 'R', 'U'};
int moveOffsets[4][2] = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}};
bool visited[30][50];
void findPath() {
Position initial;
initial.row = 0;
initial.col = 0;
initial.route = "";
visited[0][0] = true;
queue<Position> searchQueue;
searchQueue.push(initial);
while (!searchQueue.empty()) {
Position current = searchQueue.front();
searchQueue.pop();
if (current.row == 29 && current.col == 49) {
cout << current.route;
return;
}
for (int direction = 0; direction < 4; ++direction) {
Position neighbor;
neighbor.row = current.row + moveOffsets[direction][0];
neighbor.col = current.col + moveOffsets[direction][1];
if (neighbor.row < 0 || neighbor.row >= 30 || neighbor.col < 0 || neighbor.col >= 50) {
continue;
}
if (visited[neighbor.row][neighbor.col] || mazeGrid[neighbor.row][neighbor.col] == '1') {
continue;
}
visited[neighbor.row][neighbor.col] = true;
neighbor.route = current.route + directionSymbols[direction];
searchQueue.push(neighbor);
}
}
}
int main() {
for (int i = 0; i < 30; ++i) {
for (int j = 0; j < 50; ++j) {
cin >> mazeGrid[i][j];
}
}
findPath();
return 0;
}
The algorithm uses a queue to explore positions level by level, ensuring the first discovered path to the destination is the shortest. Each position tracks coordinates and the accumulated path string. Movement directions correspond to down, left, right, and up, stored in directionSymbols. The moveOffsets array defines coordinate changes for each direction. The visited array prevents revisiting cells, and walls are denoted by '1' in the grid.
Enput consists of 30 lines with 50 characters each, representing the maze layout. Output is a sequence of direction characters forming the shortest route from the top-left to bottom-right corner.