leetcode 909. Snakes and Ladders
For problems which need to find the least moves to some target, just breath-first search.
And keep three variables while searching:
- visited node to avoid repeated visit
- node queue
- current move count.
class Solution {
int[] index = new int[2];
public int snakesAndLadders(int[][] board) {
int N = board.length;
Queue<Integer> q = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
int step = 0;
q.add(0);
visited.add(0);
while (!q.isEmpty()) {
int s = q.size();
for (int i = 0; i < s; ++i) {
Integer idx = q.poll();
if (idx == N * N - 1) return step;
for (int j = 1; idx + j < N * N && j <= 6; ++j) {
computeIndex(idx + j, N);
int tx = index[0], ty = index[1];
if (board[tx][ty] != -1 ) {
if (!visited.contains(board[tx][ty] - 1)) {
q.add(board[tx][ty] - 1);
visited.add(board[tx][ty] - 1);
}
}
else {
if (!visited.contains(idx + j)) {
q.add(idx + j);
visited.add(idx + j);
}
}
}
}
step += 1;
}
return -1;
}
void computeIndex(int i, int N) {
int x = i / N;
int y = 0;
if (x % 2 == 0) y = i % N;
else y = N - (i % N) - 1;
index[0] = N - 1 - x;
index[1] = y;
}
}