zoukankan      html  css  js  c++  java
  • 计蒜客-题库-跳跃游戏

    题目

    给定一个非负整数数组,假定你的初始位置为数组第一个下标。

    数组中的每个元素代表你在那个位置能够跳跃的最大长度。

    请确认你是否能够跳跃到数组的最后一个下标。

    例如:A=[2,3,1,1,4]能够跳跃到最后一个下标,输出true

    A=[3,2,1,0,4]不能跳跃到最后一个下标,输出false

    输入格式

    第一行输入一个正整数 n(1≤n≤500),接下来的一行 n个整数,输入数组 Ai

    输出格式

    如果能跳到最后一个下标,输出true,否则输出false

    样例输入

    5
    2 0 2 0 1

    样例输出

    true

    思路

    从最后一个下标n-1往前看,依次查找能够直接到达n-1的点,然后看这些点中有没有点是可以从下标0到达的

    代码

    #include<iostream>
    using namespace std;
    int n;
    int s[500];
    int t[500] = { 0 };//用来记录结果,避免重复计算:-1表示不可达 0表示未计算 1表示可达
    //src代表终点,des代表起点
    bool dfs(int src, int des){
        if (src == 0){//src为0,表示当前就是终点,也就是能够到达
            return true;
        }
        if (des < 0){//无法到达
            return false;
        }
        if (s[des] >= src - des){//找到能直接到达src的点
            if (des == 0){//如果该点是起点,说明能从起点到达src
                return true;
            }
            if (t[des] == -1){
                return false;
            }
            if (t[des] == 0){
                if (dfs(des, des - 1)){
                    t[des] = 1;
                    return true;
                }
                else{
                    t[des] = -1;
                }
            }
            if (t[des] == 1){
                return true;
            }
        }
        if (dfs(src, des - 1)){
            return true;
        }
        return false;
    }
    int main(){
        cin >> n;
        for (int i = 0; i < n; ++i){
            cin >> s[i];
        }
        cout << (dfs(n - 1, n - 2) ? "true" : "false") << endl;
        return 0;
    }
  • 相关阅读:
    Interview with BOA
    Java Main Differences between HashMap HashTable and ConcurrentHashMap
    Java Main Differences between Java and C++
    LeetCode 33. Search in Rotated Sorted Array
    LeetCode 154. Find Minimum in Rotated Sorted Array II
    LeetCode 153. Find Minimum in Rotated Sorted Array
    LeetCode 75. Sort Colors
    LeetCode 31. Next Permutation
    LeetCode 60. Permutation Sequence
    LeetCode 216. Combination Sum III
  • 原文地址:https://www.cnblogs.com/xiangguoguo/p/6776241.html
Copyright © 2011-2022 走看看