題目地址:
https://www.lintcode.com/problem/modern-ludo-i/description
給定一個長度爲的一維棋盤,每個位置編號爲,再給定一個數組,表示棋盤的某兩個位置有連接,對於每個連接,只能從第一個位置到第二個位置,不能反向,題目保證連接的兩個位置中第一個位置編號比第二個小,並且保證第一個位置的編號一定不是。現在從這個位置開始出發,每次可以通過擲骰子走步,或者通過連接直接移動到另一個位置。問至少擲多少次骰子可以到達編號的位置。
可以用動態規劃。首先如果長度,那麼顯然只需一次。接下來開始從遍歷到,每次遍歷的時候更新後面位需要的次數,並且如果有連接,更新到達的位置的次數。代碼如下:
import java.util.*;
public class Solution {
/**
* @param length: the length of board
* @param connections: the connections of the positions
* @return: the minimum steps to reach the end
*/
public int modernLudo(int length, int[][] connections) {
// Write your code here
if (length <= 7) {
return 1;
}
Map<Integer, Set<Integer>> map = new HashMap<>();
for (int[] connection : connections) {
map.putIfAbsent(connection[0], new HashSet<>());
map.get(connection[0]).add(connection[1]);
}
int[] dp = new int[length + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
for (int i = 2; i <= 7; i++) {
dp[i] = 1;
}
for (int i = 2; i <= length; i++) {
if (map.containsKey(i)) {
for (int target : map.get(i)) {
dp[target] = Math.min(dp[target], dp[i]);
}
}
for (int j = 1; j <= 6; j++) {
if (i + j <= length) {
dp[i + j] = Math.min(dp[i + j], dp[i] + 1);
}
}
}
return dp[length];
}
}
時空複雜度。