Skip to content

Commit 9578169

Browse files
committed
Time: 4 ms (95.02%), Space: 44.2 MB (95.43%) - LeetHub
1 parent c79cac1 commit 9578169

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public int snakesAndLadders(int[][] board) {
3+
int n = board.length;
4+
int[] min_rolls = new int[n * n + 1];
5+
Arrays.fill(min_rolls, -1);
6+
Queue<Integer> q = new LinkedList<>();
7+
min_rolls[1] = 0;
8+
q.offer(1);
9+
10+
while (!q.isEmpty()) {
11+
int x = q.poll();
12+
for (int i = 1; i <= 6 && x + i <= n * n; i++) {
13+
int t = x + i;
14+
int row = (t - 1) / n;
15+
int col = (t - 1) % n;
16+
int v = board[n - 1 - row][(row % 2 == 1) ? (n - 1 - col) : col];
17+
int y = (v > 0 ? v : t);
18+
if (y == n * n) return min_rolls[x] + 1;
19+
if (min_rolls[y] == -1) {
20+
min_rolls[y] = min_rolls[x] + 1;
21+
q.offer(y);
22+
}
23+
}
24+
}
25+
return -1;
26+
}
27+
}

0 commit comments

Comments
 (0)