forked from super30admin/BFS-4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnakes-and-ladders.java
66 lines (61 loc) · 1.72 KB
/
snakes-and-ladders.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
66
//Time - O(N*N)
//Space - O(N*N)
class Solution {
public int snakesAndLadders(int[][] board) {
int minMoves = 0;
int m = board.length;
int[] moves = new int[m*m];
// flatten the board
int even = 0;
int r = m-1; int c = 0; int index = 0;
while(r>=0 && c>=0){
if(board[r][c] == -1){
moves[index] = -1;
} else {
moves[index] = board[r][c]-1;
}
index++;
if(even%2 == 0){
c++;
if(c == m){
r--;
c--;
even++;
}
} else {
c--;
if(c == -1){
r--;
c++;
even++;
}
}
}
// process the board
Queue<Integer> q = new LinkedList<>();
q.add(0);
moves[0] = -2;
while(!q.isEmpty()){
int size = q.size();
for(int i=0; i<size; i++){
int cur = q.poll();
if(cur == m*m-1) return minMoves;
for(int j=1; j<7; j++){
int nextMove = cur+j;
if(nextMove > m*m-1) break;
if(moves[nextMove] != -2){
if(moves[nextMove] == -1){
q.add(nextMove);
moves[nextMove] = -2;
} else {
q.add(moves[nextMove]);
moves[nextMove] = -2;
}
}
}
}
minMoves++;
}
return -1;
}
}