-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaze.js
66 lines (53 loc) · 1.6 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
function isOpenSpace(x, y, seed) {
return Number(x * x + 3 * x + 2 * x * y + y + y * y + seed)
.toString(2).split('')
.reduce((a, b) => a + parseInt(b), 0) % 2 === 0;
}
function shortestPath(map, from, to) {
let paths = [[[...from]]];
let nextPaths = [];
let visited = new Set();
while (paths.length) {
nextPaths = [];
for (let i = 0; i < paths.length; i++) {
const path = paths[i];
const [px, py] = path.slice(-1)[0];
const moves = [
[px, py + 1],
[px + 1, py],
[px, py - 1],
[px - 1, py],
];
for (let m = 0; m < moves.length; m++) {
const [qx, qy] = moves[m];
if (qx >= 0 && qy >= 0 && map[qy][qx] && !visited.has(`${qx},${qy}`)) {
nextPaths.push([...path, [qx, qy]]);
visited.add(`${qx},${qy}`);
}
}
}
paths = nextPaths;
for (let i = 0; i < nextPaths.length; i++) {
const path = nextPaths[i];
const [px, py] = path.slice(-1)[0];
const [tx, ty] = to;
if (px === tx && py === ty) {
return path.length - 1;
}
}
}
}
// eslint-disable-next-line no-unused-vars
function print(maze) {
console.log(maze.map((row) => row.map((t) => t ? '.' : '#').join('')).join('\n'));
}
module.exports = (input, destination) => {
const favoriteNumber = parseInt(input);
const [tx, ty] = destination.split(',').map((value) => parseInt(value));
const maze = Array
.from({ length: 50 })
.map((_, y) => Array
.from({ length: 50 })
.map((_, x) => isOpenSpace(x, y, favoriteNumber)));
return shortestPath(maze, [1, 1], [tx, ty]);
};