

class Solution {private int[] getPosition(int num, int n) {int row = n - 1 - (num - 1) / n;int col = (num - 1) / n % 2 == 0 ? (num - 1) % n : n - 1 - (num - 1) % n;return new int[]{row, col};}public int snakesAndLadders(int[][] board) {//1.定义bfs队列和visited数组int n = board.length;int target = n * n;int step = 0;Queue<Integer> queue = new LinkedList<>();boolean[] visited = new boolean[target + 1];//2.初始化bfs队列和visited数组queue.offer(1);visited[1] = true;//3.bfs算法实现while (!queue.isEmpty()) {int size = queue.size();step++;for (int i = 0; i < size; i++) {int cur = queue.poll();for (int dice = 1; dice <= 6; dice++) {int next = cur + dice;//3.1获取下一步的坐标,如果不是-1说明可以传送int[] position = getPosition(next, n);int row = position[0], col = position[1];next = board[row][col] == -1 ? next : board[row][col];//3.2抵达终点直接返回步骤数if (next == target) {return step;}//3.3下一步未被访问过则入队列并标记访问过if (!visited[next]) {visited[next] = true;queue.offer(next);}}}}//4.不能抵达终点返回-1return -1;}
}