Check if There is a Valid Path in a Grid LeetCode solution in JavaScript
1// Memory Usage: 50.9 MB, less than 100.00%2var hasValidPath = function (grid) {3if (grid[0][0] === 5) return false;45const M = grid.length,6N = grid[0].length;7const SEGMENTS = {81: {9dirs: [10[0, -1],11[0, 1],12],13adjs: [14[1, 4, 6],15[1, 3, 5],16],17},182: {19dirs: [20[-1, 0],21[1, 0],22],23adjs: [24[2, 3, 4],25[2, 5, 6],26],27},283: {29dirs: [30[0, -1],31[1, 0],32],33adjs: [34[1, 4, 6],35[2, 5, 6],36],37},384: {39dirs: [40[0, 1],41[1, 0],42],43adjs: [44[1, 3, 5],45[2, 5, 6],46],47},485: {49dirs: [50[-1, 0],51[0, -1],52],53adjs: [54[2, 3, 4],55[1, 4, 6],56],57},586: {59dirs: [60[-1, 0],61[0, 1],62],63adjs: [64[2, 3, 4],65[1, 3, 5],66],67},68};69let path = Array.from(70{ length: grid.length },71(el) => new Uint16Array(grid[0].length)72);73let y = 0,74x = 0;7576function getNextSegment(segment, y, x) {77let dir = 0;78let ny = y + SEGMENTS[segment].dirs[dir][0];79let nx = x + SEGMENTS[segment].dirs[dir][1];80if (ny < 0 || ny >= M || nx < 0 || nx >= N || path[ny][nx]) {81dir = 1;82ny = y + SEGMENTS[segment].dirs[dir][0];83nx = x + SEGMENTS[segment].dirs[dir][1];84}85return { dir, ny, nx };86}8788function isValid(y, x) {89for (let i = 0; i < M * N; i++) {90if (y == M - 1 && x == N - 1) return true;91path[y][x] = i + 1;92let cur = grid[y][x];93let next = getNextSegment(cur, y, x);94if (next.ny >= M || next.nx >= N) return false;95if (!SEGMENTS[cur].adjs[next.dir].includes(grid[next.ny][next.nx]))96return false;97y = next.ny;98x = next.nx;99}100return false;101}102103if (grid[0][0] !== 4) return isValid(y, x);104path[0][0] = 1;105return isValid(y, x + 1) || isValid(y + 1, x);106};