This commit is contained in:
kkunkka
2025-07-26 14:01:50 +08:00
parent 073d099577
commit dc614a018d

View File

@@ -0,0 +1,51 @@
package com.dota.gridGraph._909;
import java.util.ArrayDeque;
class Solution {
public int snakesAndLadders(int[][] board) {
var cnt = -1;
int n = board.length;
var book = new boolean[n * n + 1];
var queue = new ArrayDeque<Integer>();
queue.add(1);
while (!queue.isEmpty()) {
cnt++;
int size = queue.size();
for (int s = 0; s < size; s++) {
int p = queue.poll();
if (p == n * n) {
return cnt;
}
for (int i = 1; i <= 6 && p + i <= n * n; i++) {
var next = p + i;
if (book[next]) continue;
var xy = getXy(next, n);
var x = xy[0];
var y = xy[1];
book[next] = true;
if (board[x][y] == -1) {
queue.offer(next);
continue;
}
//跳到下一步
queue.offer(board[x][y]);
}
}
}
return -1;
}
// k是编号
// 从编号获取坐标
int[] getXy(int no, int n) {
var m = (no - 1) / n;
var l = (no - 1) % n;
if (m % 2 == 1) {
return new int[]{n - 1 - m, n - l - 1};
}
return new int[]{n - 1 - m, l};
}
}