Check if There is a Valid Path in a Grid LeetCode solution in JavaScript

1
// Memory Usage: 50.9 MB, less than 100.00%
2
var hasValidPath = function (grid) {
3
if (grid[0][0] === 5) return false;
4

5
const M = grid.length,
6
N = grid[0].length;
7
const SEGMENTS = {
8
1: {
9
dirs: [
10
[0, -1],
11
[0, 1],
12
],
13
adjs: [
14
[1, 4, 6],
15
[1, 3, 5],
16
],
17
},
18
2: {
19
dirs: [
20
[-1, 0],
21
[1, 0],
22
],
23
adjs: [
24
[2, 3, 4],
25
[2, 5, 6],
26
],
27
},
28
3: {
29
dirs: [
30
[0, -1],
31
[1, 0],
32
],
33
adjs: [
34
[1, 4, 6],
35
[2, 5, 6],
36
],
37
},
38
4: {
39
dirs: [
40
[0, 1],
41
[1, 0],
42
],
43
adjs: [
44
[1, 3, 5],
45
[2, 5, 6],
46
],
47
},
48
5: {
49
dirs: [
50
[-1, 0],
51
[0, -1],
52
],
53
adjs: [
54
[2, 3, 4],
55
[1, 4, 6],
56
],
57
},
58
6: {
59
dirs: [
60
[-1, 0],
61
[0, 1],
62
],
63
adjs: [
64
[2, 3, 4],
65
[1, 3, 5],
66
],
67
},
68
};
69
let path = Array.from(
70
{ length: grid.length },
71
(el) => new Uint16Array(grid[0].length)
72
);
73
let y = 0,
74
x = 0;
75

76
function getNextSegment(segment, y, x) {
77
let dir = 0;
78
let ny = y + SEGMENTS[segment].dirs[dir][0];
79
let nx = x + SEGMENTS[segment].dirs[dir][1];
80
if (ny < 0 || ny >= M || nx < 0 || nx >= N || path[ny][nx]) {
81
dir = 1;
82
ny = y + SEGMENTS[segment].dirs[dir][0];
83
nx = x + SEGMENTS[segment].dirs[dir][1];
84
}
85
return { dir, ny, nx };
86
}
87

88
function isValid(y, x) {
89
for (let i = 0; i < M * N; i++) {
90
if (y == M - 1 && x == N - 1) return true;
91
path[y][x] = i + 1;
92
let cur = grid[y][x];
93
let next = getNextSegment(cur, y, x);
94
if (next.ny >= M || next.nx >= N) return false;
95
if (!SEGMENTS[cur].adjs[next.dir].includes(grid[next.ny][next.nx]))
96
return false;
97
y = next.ny;
98
x = next.nx;
99
}
100
return false;
101
}
102

103
if (grid[0][0] !== 4) return isValid(y, x);
104
path[0][0] = 1;
105
return isValid(y, x + 1) || isValid(y + 1, x);
106
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0