-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrat-in-maze-backtracking.js
77 lines (65 loc) · 1.54 KB
/
rat-in-maze-backtracking.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const maze = [
[ 1, 0, 0, 0 ],
[ 1, 1, 0, 1 ],
[ 1, 0, 0, 0 ],
[ 1, 1, 1, 1 ],
];
class MazeBacktrack {
constructor(maze) {
if (!Array.isArray(maze) || maze.length === 0) {
throw new Error('Maze should be an array with more than one row');
}
this.maze = maze;
this.numberOfRows = maze.length;
this.numberOfColumns = maze[0].length;
this.exitRow = this.numberOfRows - 1;
this.exitColumn = this.numberOfColumns - 1;
this.directions = [
[ 0, 1 ], // FORWARD
[ 1, 0 ], // DOWN
];
this.clearSolution();
}
clearSolution() {
this.solution = new Array(this.numberOfRows)
.fill(null)
.map(() => new Array(this.numberOfColumns).fill(0));
}
isValid(i, j) {
return (
i >= 0 &&
i < this.numberOfRows &&
j >= 0 &&
j < this.numberOfColumns &&
this.maze[i][j] === 1
);
}
/**
*
* @param {number} i
* @param {number} j
* @time complexity: O(2^(N^2))
* @space complexity: O(N^2)
*/
dfs(i = 0, j = 0) {
if (!this.isValid(i, j)) {
return false;
}
// MARK CURRENT BLOCK AS PART OF THE SOLUTION
this.solution[i][j] = 1;
// READ THE DESINTATION
if (i === this.exitRow && j === this.exitColumn) {
return this.solution;
}
for (const [x, y] of this.directions) {
if (this.dfs(i + x, j + y)) {
return this.solution;
}
}
// UNMARK CURRENT BLOCK
this.solution[i][j] = 0;
return false;
}
}
const solve = new MazeBacktrack(maze);
console.log(solve.dfs());