-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy path_909.java
66 lines (60 loc) · 1.82 KB
/
_909.java
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
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
/**
* LeetCode 909 - Snakes and Ladders
*
* BFS
* Need to read the problem description carefully...
*/
public class _909 {
public int snakesAndLadders(int[][] board) {
int n = board.length;
int[] board1D = new int[n * n + 1];
int idx = 0;
for (int i = n - 1; i >= 0; i--) {
if ((i - (n - 1)) % 2 == 0) {
for (int j = 0; j < n; j++) {
idx++;
board1D[idx] = board[i][j];
}
} else {
for (int j = n - 1; j >= 0; j--) {
idx++;
board1D[idx] = board[i][j];
}
}
}
Queue<Integer> queue = new ArrayDeque<>();
Map<Integer, Integer> dist = new HashMap<>();
queue.add(1);
dist.put(1, 0);
while (!queue.isEmpty()) {
int u = queue.poll();
for (int i = u + 1; i <= u + 6 && i <= n * n; i++) {
int v = board1D[i] == -1 ? i : board1D[i];
if (!dist.containsKey(v)) {
dist.put(v, dist.get(u) + 1);
if (v == n * n) {
return dist.get(v);
}
queue.add(v);
}
}
}
return -1;
}
public static void main(String[] args) {
_909 sol = new _909();
int[][] board = {
{-1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1},
{-1, 35, -1, -1, 13, -1},
{-1, -1, -1, -1, -1, -1},
{-1, 15, -1, -1, -1, -1},
};
System.out.println(sol.snakesAndLadders(board));
}
}