题目
https://leetcode-cn.com/problems/snakes-and-ladders/
代码
class Solution {
int N;
public int snakesAndLadders(int[][] board) {
N=board.length;
boolean[] vis=new boolean[N*N+1];//默认false
LinkedList<int[]> queue=new LinkedList<>();
queue.add(new int[]{1,0});
while(!queue.isEmpty()){
int[] p=queue.poll();//弹出最前面的
int x=p[0];
int step=p[1];
for(int i=x+1;i<=x+6;i++){
if(i>N*N)
break;
int[] rc=cal(i);
int row=rc[0];
int col=rc[1];
int next=i;
if(row<0||row>N||col<0||col>N)
continue;
if(board[row][col]>0){
next=board[row][col];
}
if(next==N*N){
return step+1;
}
if(!vis[next]){
vis[next]=true;
queue.add(new int[]{next,step+1});
}
}
}
return -1;
}
//计算行列
public int[] cal(int x){
int r = (x - 1) / N;
int c = (x - 1) % N;
if (r % 2 == 1) {
c = N - 1 - c;
}
return new int[]{N - 1 - r, c};//这里行的转化为什么不放在上面,因为列的转换需要行的原值,不然就错了
}
}