【Leetcode】909. Snakes and Ladders
阿新 • • 發佈:2021-01-25
技術標籤:# DFS、BFS與圖論leetcode演算法java
題目地址:
https://leetcode.com/problems/snakes-and-ladders/
給定一個
N
×
N
N\times N
N×N棋盤
A
A
A,對每個格子進行編號,從最左下角開始從
1
1
1編號,向右依次
2
,
3
,
.
.
.
,
N
2,3,...,N
2,3,...,N,走到最右邊則向上走一步是
N
+
1
N+1
N+1,然後一路再向左依次是
N
+
2
,
N
+
3
,
.
.
.
,
2
N
N+2,N+3,...,2N
N+2,N+3,...,2N,這樣走到第
0
0
0行直至走到
N
2
N^2
N2這個位置。從編號
1
1
1的位置出發,每次處於
a
a
a的時候,可以走到
a
+
j
,
j
=
1
,
2
,
.
.
.
,
6
a+j,j=1,2,...,6
a+j,j=1,2,...,6這些位置(當然這些位置的編號不能超出
N
2
N^2
N2),如果
A
A
A在這個位置不等於
−
1
-1
−1,那麼就需要瞬間移動到
A
A
A在此處的值對應的編號的位置(瞬移是強制的,不消耗步數)。問從
1
1
1出發至少需要走多少步能走到
N
2
N^2
N2這個位置。題目保證
A
[
N
−
1
]
[
0
]
=
−
1
A[N-1][0]=-1
A[N−1 ][0]=−1,並且
N
>
1
N>1
N>1。
參考https://blog.csdn.net/qq_46105170/article/details/110944757。程式碼如下:
import java.util.ArrayDeque;
import java.util.Queue;
public class Solution {
public int snakesAndLadders(int[][] board) {
int n = board.length;
// 一定要注意起點終點重合的情況
if (n == 1) {
return 0;
}
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(0);
boolean[] visited = new boolean[n * n];
visited[0] = true;
int res = 0;
while (!queue.isEmpty()) {
res++;
int size = queue.size();
for (int i = 0; i < size; i++) {
int cur = queue.poll();
for (int j = 1; j <= 6; j++) {
if (cur + j == n * n - 1) {
return res;
}
if (cur + j >= n * n) {
break;
}
int[] nextPos = transform(cur + j, n);
int x = nextPos[0], y = nextPos[1];
// 如果需要瞬移,則強制瞬移
if (board[x][y] != -1) {
if (board[x][y] == n * n) {
return res;
}
if (!visited[board[x][y] - 1]) {
visited[board[x][y] - 1] = true;
queue.offer(board[x][y] - 1);
}
continue;
}
if (!visited[cur + j]) {
visited[cur + j] = true;
queue.offer(cur + j);
}
}
}
}
return -1;
}
private int[] transform(int x, int n) {
return new int[]{n - 1 - x / n, x / n % 2 == 0 ? x % n : n - 1 - x % n};
}
}
時空複雜度 O ( n 2 ) O(n^2) O(n2)。