-
Notifications
You must be signed in to change notification settings - Fork 0
/
maze.js
56 lines (46 loc) · 1.37 KB
/
maze.js
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
function solveMaze(maze, start, end) {
const rows = maze.length;
const cols = maze[0].length;
const visited = Array.from(Array(rows), () => new Array(cols).fill(false));
const path = [];
const isSafe = (row, col) => {
return row >= 0 && row < rows && col >= 0 && col < cols && maze[row][col] === 1 && !visited[row][col];
};
const dfs = (row, col) => {
if (row === end[0] && col === end[1]) {
path.push([row, col]);
return true;
}
if (isSafe(row, col)) {
visited[row][col] = true;
path.push([row, col]);
// Try moving in all four directions
if (dfs(row + 1, col) || dfs(row - 1, col) || dfs(row, col + 1) || dfs(row, col - 1)) {
return true;
}
// Backtrack if no path found from this cell
path.pop();
}
return false;
};
if (!dfs(start[0], start[1])) {
return []; // No solution found
}
return path;
}
const maze = [
[1, 0, 1, 1, 1],
[1, 1, 1, 0, 1],
[0, 0, 1, 0, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 0, 1]
];
const end = [4, 4];
const start = [0, 0];
const solution = solveMaze(maze, start, end);
if (solution.length > 0) {
console.log("Solution path:");
solution.forEach(coord => console.log(coord));
} else {
console.log("No solution found.");
}