-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmaze.js
96 lines (83 loc) · 2.61 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
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
87
88
89
90
91
92
93
94
95
96
const VISITED = 1;
const UNVISITED = 0;
const BLOCKED = -1;
const DESTINATION = 2;
const isSafe = (startX, startY) => {
return (
startX >= 0 &&
startY >= 0 &&
startX < maze.length &&
startY < maze[startX].length &&
maze[startX][startY] !== VISITED &&
maze[startX][startY] !== BLOCKED
);
};
const visitCell = (startX, startY) => {
maze[startX][startY] = VISITED;
path.push({ startX, startY });
};
const travelMaze = (startX, startY) => {
console.log(startX, startY);
if (isSafe(startX, startY)) {
//if it reaches the destination
if (maze[startX][startY] === DESTINATION) {
path.push({ startX, startY });
console.log(path);
return true;
} else {
// visit the cell
visitCell(startX, startY);
//go front
if (travelMaze(startX, startY + 1)) {
return true;
}
//go back
if (travelMaze(startX, startY - 1)) {
return true;
}
//go up
if (travelMaze(startX - 1, startY)) {
return true;
}
//go down
if (travelMaze(startX + 1, startY)) {
return true;
}
// remove the path
path.pop();
return false;
}
}
return false;
};
let path = [];
//solution possible if the rat can move just in a couple of directions
const maze = [
[UNVISITED, BLOCKED, BLOCKED, BLOCKED],
[UNVISITED, UNVISITED, UNVISITED, UNVISITED],
[BLOCKED, UNVISITED, BLOCKED, BLOCKED],
[UNVISITED, UNVISITED, UNVISITED, DESTINATION]
];
// solution possible only if it moves in all directions
// const maze = [
// [UNVISITED, BLOCKED, UNVISITED, UNVISITED, UNVISITED],
// [UNVISITED, UNVISITED, UNVISITED, BLOCKED, UNVISITED],
// [UNVISITED, BLOCKED, BLOCKED, UNVISITED, UNVISITED],
// [UNVISITED, BLOCKED, BLOCKED, UNVISITED, BLOCKED],
// [UNVISITED, BLOCKED, BLOCKED, UNVISITED, DESTINATION]
// ];
// const maze = [
// [BLOCKED, UNVISITED, UNVISITED, UNVISITED, BLOCKED, UNVISITED],
// [UNVISITED, BLOCKED, UNVISITED, UNVISITED, BLOCKED, UNVISITED],
// [UNVISITED, BLOCKED, UNVISITED, BLOCKED, UNVISITED, UNVISITED],
// [UNVISITED, BLOCKED, UNVISITED, UNVISITED, BLOCKED, BLOCKED],
// [UNVISITED, UNVISITED, UNVISITED, UNVISITED, BLOCKED, UNVISITED],
// [UNVISITED, BLOCKED, UNVISITED, UNVISITED, UNVISITED, DESTINATION]
// ];
// console.log(maze);
travelMaze(0, 0);
// console.log(maze);
// path.concat and path.slice clones creates a new copy of the array
// path.pop and path.push mutates the array so modifies the array; there is always one copy of the array available
// string works because string by default is immutable by nature
// return always returns to the caller