class MazeSolver {
maze: number[][];
n: number;
path: number[][];
constructor(maze: number[][]) {
this.maze = maze;
this.n = maze.length;
this.path = Array.from({ length: this.n }, () => Array(this.n).fill(0));
}
isSafe(x: number, y: number): boolean {
return x >= 0 && y >= 0 && x < this.n && y < this.n && this.maze[x][y] === 1;
}
solve(): boolean {
if (this.solveUtil(0, 0)) {
this.printPath();
return true;
} else {
console.log('No path found');
return false;
}
}
solveUtil(x: number, y: number): boolean {
if (x === this.n - 1 && y === this.n - 1 && this.maze[x][y] === 1) {
this.path[x][y] = 1;
return true;
}
if (this.isSafe(x, y)) {
if (this.path[x][y] === 1) return false; // already visited
this.path[x][y] = 1; // mark path
if (this.solveUtil(x + 1, y)) return true; // move down
if (this.solveUtil(x, y + 1)) return true; // move right
this.path[x][y] = 0; // backtrack
return false;
}
return false;
}
printPath(): void {
let result = '';
for (let i = 0; i < this.n; i++) {
for (let j = 0; j < this.n; j++) {
result += this.path[i][j] + ' ';
}
result += '\n';
}
console.log(result.trim());
}
}
const maze = [
[1, 0, 0],
[1, 1, 0],
[0, 1, 1]
];
const solver = new MazeSolver(maze);
solver.solve();if (x === this.n - 1 && y === this.n - 1 && this.maze[x][y] === 1) {
check if current cell is goal and open
check if current cell is within bounds and open
if (this.path[x][y] === 1) return false;
avoid revisiting cells to prevent loops
mark current cell as part of path
if (this.solveUtil(x + 1, y)) return true;
try moving down
if (this.solveUtil(x, y + 1)) return true;
try moving right
backtrack if no path found from current cell