-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnakes-and-ladders.js
More file actions
79 lines (66 loc) · 1.94 KB
/
snakes-and-ladders.js
File metadata and controls
79 lines (66 loc) · 1.94 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
72
73
74
75
76
77
78
79
/**
* Problem: Snakes and Ladders
* Link: https://leetcode.com/problems/snakes-and-ladders/
* Difficulty: Medium
*
* Find minimum dice rolls to reach the last square. BFS on the board.
*
* Time Complexity: O(n²)
* Space Complexity: O(n²)
*/
// JavaScript Solution — BFS
function snakesAndLadders(board) {
const n = board.length;
const target = n * n;
// Convert board position (1-indexed) to row,col
function getRowCol(pos) {
const r = Math.floor((pos - 1) / n);
const c = (pos - 1) % n;
const row = n - 1 - r; // board is bottom-to-top
const col = r % 2 === 0 ? c : n - 1 - c; // alternating direction
return [row, col];
}
const visited = new Set([1]);
const queue = [[1, 0]]; // [position, rolls]
while (queue.length) {
const [pos, rolls] = queue.shift();
for (let dice = 1; dice <= 6; dice++) {
let next = pos + dice;
if (next > target) continue;
const [r, c] = getRowCol(next);
if (board[r][c] !== -1) next = board[r][c]; // snake or ladder
if (next === target) return rolls + 1;
if (!visited.has(next)) {
visited.add(next);
queue.push([next, rolls + 1]);
}
}
}
return -1;
}
module.exports = snakesAndLadders;
/* Python Solution:
from collections import deque
def snakesAndLadders(board):
n = len(board)
target = n * n
def get_rc(pos):
r, c = divmod(pos - 1, n)
row = n - 1 - r
col = c if r % 2 == 0 else n - 1 - c
return row, col
visited = {1}
queue = deque([(1, 0)])
while queue:
pos, rolls = queue.popleft()
for dice in range(1, 7):
nxt = pos + dice
if nxt > target: continue
r, c = get_rc(nxt)
if board[r][c] != -1: nxt = board[r][c]
if nxt == target: return rolls + 1
if nxt not in visited:
visited.add(nxt)
queue.append((nxt, rolls + 1))
return -1
*/