There was an error while loading. Please reload this page.
1 parent c79cac1 commit 9578169Copy full SHA for 9578169
0945-snakes-and-ladders/0945-snakes-and-ladders.java
@@ -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