【Lintcode】1565. Modern Ludo I

題目地址:

https://www.lintcode.com/problem/modern-ludo-i/description

給定一個長度爲ll的一維棋盤,每個位置編號爲1l1\sim l,再給定一個數組,表示棋盤的某兩個位置有連接,對於每個連接,只能從第一個位置到第二個位置,不能反向,題目保證連接的兩個位置中第一個位置編號比第二個小,並且保證第一個位置的編號一定不是11。現在從11這個位置開始出發,每次可以通過擲骰子走161\sim 6步,或者通過連接直接移動到另一個位置。問至少擲多少次骰子可以到達ll編號的位置。

可以用動態規劃。首先如果長度l7l\le 7,那麼顯然只需一次。接下來開始從22遍歷到ll,每次遍歷的時候更新後面66位需要的次數,並且如果有連接,更新到達的位置的次數。代碼如下:

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];
    }
}

時空複雜度O(n)O(n)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章