---
# System prepended metadata

title: 45. Jump Game II
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}    
/* 設定連結 */
a,
.open-files-container li.selected a {
    color: #89FFF8;
    
}
a:hover,
.open-files-container li.selected a:hover {
    color: #89FFF890;
}
   
</style>

###### tags: `Leetcode`

# 45. Jump Game II


###### Link : https://leetcode.com/problems/jump-game-ii/description/

## 題目



## 程式碼I
```cpp=
class Solution {
public:
    int jump(vector<int>& nums) {
        const int n = nums.size();
        if(n == 1) return 0;
        vector<bool> flag(n, 0);
        queue<int> q;
        q.push(0);
        int cnt = 1;//走到第幾步
        while(true){
            int times = q.size();//queue這次需拿出多少個
            for(int i = 0;i < times;i++){
                int index = q.front(); q.pop();
                for(int j = 1;j <= nums[index];++j){
                    //走到n - 1回傳目前步數
                    if(index + j == n - 1) return cnt;
                    else if(!flag[index + j]){//如果沒走過
                        q.push(index + j);//放進queue
                        flag[index + j] = true;//標記走過
                    }
                }
            }
            ++cnt;
        }
        return -1;
    }
};
```

## 程式碼II (Better Solution)
```cpp=
class Solution {
public:
    int jump(vector<int>& nums) {
        const int n = nums.size();
        int curEnd = 0, curFar = 0, ans = 0;
        for(int i = 0;i < n - 1;++i){
            //下一步最遠可以走到
            curFar = max(curFar, i + nums[i]);
            //如果走到目前步數的最後一個位置
            if(i == curEnd){
                //更新下一步最遠可以走到的位置
                curEnd = curFar;
                ++ans;//步數+1
            }
        }
        return ans;
    }
};
```
## Date 
### 2023/2/8