欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[leetcode] Jump Game II

程序员文章站 2024-03-01 09:09:52
...

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
    Jump 1 step from index 0 to 1, then 3 steps to the last index.

Note:
You can assume that you can always reach the last index.

Solution

使用广搜。

class Solution {
 public:
  int jump(vector<int>& nums) {
    // 数组为空,不需要移动。
    if (!nums.size()) {
      return 0;
    }
    queue<int> indexes;
    int min_road_length = 0, temp, current_index = 0, length = nums.size() - 1, max = 0;
    indexes.push(0);
    indexes.push(-1);
    // 广搜
    while (current_index < length && indexes.size()) {
      current_index = indexes.front();
      indexes.pop();
      if (current_index == -1) {
        indexes.push(-1);
        min_road_length = min_road_length + 1;
      } else {
        temp = nums[current_index];
        if (current_index + temp >= length) {
          min_road_length = min_road_length + 1;
          break;
        }
        while (temp && current_index + temp > max) {
          indexes.push(current_index + temp);
          temp = temp - 1;
        }
        max = max < current_index + temp ? current_index + temp : max;
      }
    }
    return min_road_length;
  }
};
相关标签: cpp