Problem : https://leetcode.com/problems/snakes-and-ladders/description/
This problem can be solved with BFS algorithm.
Each square on the board might be visited by regular visit or by using a ladder. So each square has 2 visited states. Start from the index 1 square and use BFS algorithm to find the least steps to reach to the N*N square.
class Solution {
public int snakesAndLadders(int[][] board) {
int N = board.length;
// Every square may be visited by a regular movement or by using a ladder
boolean[][] visited = new boolean[N*N+1][2];
Deque<Integer> queue = new LinkedList<>();
queue.offerLast(1);
visited[1][0] = true;
int result = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int currentIndex = queue.pollFirst();
// reach the destination
if (currentIndex == N*N) {
return result;
}
for (int j = 1; j <= 6 && currentIndex + j <= N * N; j++) {
int nextIndex = currentIndex + j;
int[] nextPos = indexToPos(nextIndex, N);
if (board[nextPos[0]][nextPos[1]] != -1) {
// if the square has ladder
int jumpIndex = board[nextPos[0]][nextPos[1]];
// check if this square has been visited by using ladder
if (visited[jumpIndex][1]) {
continue;
}
visited[jumpIndex][1] = true;
queue.offerLast(jumpIndex);
} else {
// if this square has been visited by regular movement
if (visited[nextIndex][0]) {
continue;
}
visited[nextIndex][0] = true;
queue.offerLast(nextIndex);
}
}
}
result += 1;
}
return -1;
}
int[] indexToPos(int i, int N) {
// find the row index
int y = (N - 1) - (i-1) / N;
// find the column index
int x = (i-1) % N;
// revert the column order on the row "y" if it is needed
if (y % 2 == N % 2) {
x = (N-1) - x;
}
return new int[] { y, x };
}
}
No comments:
Post a Comment