-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0909-snakes-and-ladders.js
More file actions
71 lines (59 loc) · 2.1 KB
/
0909-snakes-and-ladders.js
File metadata and controls
71 lines (59 loc) · 2.1 KB
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
67
68
69
70
71
/**
* Snakes And Ladders
* Time Complexity: O(N^2)
* Space Complexity: O(N^2)
*/
var snakesAndLadders = function (board) {
const boardLengthValue = board.length;
const maxSquareNumber = boardLengthValue * boardLengthValue;
const squaresToVisitQueue = [1];
const visitedPathNodes = new Set([1]);
let minimumRolls = 0;
const calculateCellCoordinates = (coordInputSquare, gridSizeParameter) => {
const zeroIndexedValue = coordInputSquare - 1;
const invertedRowIndex = Math.floor(zeroIndexedValue / gridSizeParameter);
const absoluteBoardRow = gridSizeParameter - 1 - invertedRowIndex;
const isOddRowFromBottom = invertedRowIndex % 2 !== 0;
let calculatedBoardColumn;
if (isOddRowFromBottom) {
calculatedBoardColumn =
gridSizeParameter - 1 - (zeroIndexedValue % gridSizeParameter);
} else {
calculatedBoardColumn = zeroIndexedValue % gridSizeParameter;
}
return [absoluteBoardRow, calculatedBoardColumn];
};
while (squaresToVisitQueue.length > 0) {
const currentLevelCount = squaresToVisitQueue.length;
for (
let levelTraversalIndex = 0;
levelTraversalIndex < currentLevelCount;
levelTraversalIndex++
) {
const currentLocationSquare = squaresToVisitQueue.shift();
if (currentLocationSquare === maxSquareNumber) {
return minimumRolls;
}
for (let diceOutcome = 1; diceOutcome <= 6; diceOutcome++) {
const possibleNextSquare = currentLocationSquare + diceOutcome;
if (possibleNextSquare > maxSquareNumber) {
continue;
}
const [targetCellRow, targetCellCol] = calculateCellCoordinates(
possibleNextSquare,
boardLengthValue,
);
const finalMoveDestination =
board[targetCellRow][targetCellCol] === -1
? possibleNextSquare
: board[targetCellRow][targetCellCol];
if (!visitedPathNodes.has(finalMoveDestination)) {
visitedPathNodes.add(finalMoveDestination);
squaresToVisitQueue.push(finalMoveDestination);
}
}
}
minimumRolls++;
}
return -1;
};