LeetCode#55. Jump Game

topic:

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.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

Title:

This problem can be solved by using a queue. By applying the idea of ​​BFS, an int queue q is created, and a variable max_num records the maximum jump distance, which is initially recorded as 0

For example the first case A =  [2,3,1,1,4].

The initial queue q is empty, and the first position 0 is added to the queue.

nums[0] = 2, this position can jump back two positions, then add 1 and 2 to the queue, remove 0 from the queue, and update max_num = 2.

Take the first element of the queue 1, nums[1]= 3, you can jump back 3 positions, the farthest can be adjusted to 4, 4 > max_num, add 2, 3, 4 to the queue, because 2 is already in the queue at this time , so there is no need to consider it, because 4 is the end point, so the sequence can reach the end point.

A C++ implementation method is as follows:

#include<iostream>
#include<vector>
#include<queue>
#include<iterator>
using namespace std;

class Solution {
public:
    bool canJump(vector<int>& nums) {
        queue<int> q;
        int last_index = nums.size()-1;
        if(nums.size() == 0 || nums.size() == 1) return true;
        q.push(0);
        int pos = 0;
        int max_num = 0;
        while(!q.empty()) {
        	int index = nums[pos];
            //If the farthest position that the current team leader can jump to is less than the farthest position that has been reached so far, there is no need to add any positions to the queue, because these positions are already in the queue
        	if(max_num < pos+index) {
                //Add the farthest position in the current queue to the farthest position the team leader can reach into the queue
        		for(int i = max_num+1; i <= pos+index; i++) {
        			if(i == last_index) {
        				return true;
					}
					if(i > max_num) {
						q.push(i);
					}
				}
			}
            //update the farthest position
			if(max_num <= pos+index) {
				max_num = pos+index;
			}
			q.pop();
			pos = q.front();
		}
		return false;
    }
};



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325401158&siteId=291194637