Minimum Moves to Reach Target with Rotations LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} grid
3
* @return {number}
4
*/
5
var minimumMoves = function (grid) {
6
const len = grid.length;
7
const initPosition = [0, true, 1];
8
const visited = new Set([initPosition.join()]);
9

10
const queue = new Queue();
11
initPosition.push(0);
12
queue.enqueue(initPosition);
13
while (!queue.isEmpty()) {
14
let [row, isHorizontal, col, numMoves] = queue.dequeue();
15
if (row + col === len * 2 - 2 && isHorizontal) return numMoves;
16
numMoves++;
17
const positions = [];
18
if (isHorizontal) {
19
if (grid[row][col + 1] === 0) {
20
positions.push([row, true, col + 1]);
21
}
22
if (
23
row + 1 < len &&
24
grid[row + 1][col - 1] === 0 &&
25
grid[row + 1][col] === 0
26
) {
27
positions.push([row + 1, true, col]);
28
positions.push([row + 1, false, col - 1]);
29
}
30
} else {
31
if (row + 1 < len && grid[row + 1][col] === 0) {
32
positions.push([row + 1, false, col]);
33
}
34
if (row > 0 && grid[row - 1][col + 1] === 0 && grid[row][col + 1] === 0) {
35
positions.push([row, false, col + 1]);
36
positions.push([row - 1, true, col + 1]);
37
}
38
}
39
for (let position of positions) {
40
const str = position.join();
41
if (visited.has(str)) continue;
42
visited.add(str);
43
position.push(numMoves);
44
queue.enqueue(position);
45
}
46
}
47
return -1;
48
};
49

50
class Queue {
51
constructor() {
52
this.head = { next: null };
53
this.tail = this.head;
54
}
55

56
isEmpty() {
57
return this.head.next === null;
58
}
59

60
dequeue() {
61
const { value } = this.head.next;
62
this.head = this.head.next;
63
return value;
64
}
65

66
enqueue(value) {
67
this.tail.next = { value, next: null };
68
this.tail = this.tail.next;
69
}
70
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0