-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathhuntMatrix.js
More file actions
43 lines (36 loc) · 766 Bytes
/
huntMatrix.js
File metadata and controls
43 lines (36 loc) · 766 Bytes
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
let test = [[1, 1, 1],
[0, 0, 1],
[0, 2, 1]];
function ratPath(matrix) {
let result;
let visited = new Set();
function hunt(x, y, path) {
let key = x + '_' + y;
if (x < 0 || y < 0 || x >= matrix[0].length || y >= matrix.length) {
return;
}
if (matrix[y][x] === 0) {
return;
}
if (visited.has(key)) {
return;
}
if (matrix[y][x] === 2) {
path.push([x, y]);
result = path.slice();
path.pop();
return;
}
path.push([x, y]);
visited.add(key);
hunt(x+1, y, path);
hunt(x-1, y, path);
hunt(x, y+1, path);
hunt(x, y-1, path);
path.pop();
visited.delete(key);
}
hunt(0, 0, []);
return result;
}
console.log(ratPath(test));