-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnakesAndLadders.java
More file actions
48 lines (37 loc) · 1.14 KB
/
SnakesAndLadders.java
File metadata and controls
48 lines (37 loc) · 1.14 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
package graph;
import java.util.LinkedList;
import java.util.Queue;
public class SnakesAndLadders {
public int snakesAndLadders(int[][] board) {
int n = board.length, end = n * n, result = 0;
Queue<Integer> q = new LinkedList<>();
q.add(1);
while (!q.isEmpty()) {
result++;
int size = q.size();
while (size-- > 0) {
int curr = q.poll();
for (int i = 1; i <= 6; i++) {
int next = curr + i;
int[] rc = getRowCol(next, n);
next = board[rc[0]][rc[1]] == -1 ? next : board[rc[0]][rc[1]];
if (next == -2) continue;
if (next >= end) return result;
q.add(next);
board[rc[0]][rc[1]] = -2;
}
}
}
return -1;
}
private int[] getRowCol(int num, int n) {
num--;
int r = n - 1 - num / n, c;
if (((n - 1) & 1) == (r & 1)) {
c = num % n;
} else {
c = n - num % n - 1;
}
return new int[]{r, c};
}
}