Greedy algorithm-Jumping Game II

Source: Internet
Author: User

Given a non-negative integer array, assume that your initial position is the first subscript of the array.

Each element in the array represents the maximum length that you can jump in that position.

Your goal is to reach the last subscript and use the fewest jumps.

For example:

A=[2,3,1,1,4], the minimum number of hops to reach the last subscript is2. (Jump First< Span class= "base textstyle uncramped" >1  step, from subscript  0  to  < Span class= "katex-html" >< Span class= "Mord MATHRM" >1, then jumps  < span class= "Strut" > 3 , < Span class= "Strut bottom" >< Span class= "Katex-mathml" > reached the last subscript. Total two times)

Input Format

The first line enters a positive integern (1 ≤n≤1 00)   On the next line, enter < Span class= "base textstyle uncramped" >n  integers, representing arrays a.

output Format

The last minimum number of hops is output.

Sample Input
5 3 1 1 1 1
Sample output
2

Analysis:

Through the above example analysis, similar to the greedy algorithm, each jump step, the number of steps cnt++, and then determine the next jump the furthest distance, until the arrival of S[n-1], as shown:

The code is as follows:

#include <stdio.h>intn,s[10000]={0},ct=0; intBFsinti) {intk,j=0, l,max=0; if(i>=n-1)return 0;//Find and Exitk=s[i];ct++; if(i+k>=n-1)return 0;//Find and Exit      for(l=i+1; l<=i+k;l++)//for () find the next time you can jump to the farthest distance     {                   if(Max<=l+s[l])//Update Data{J=l;max=l+S[l];          }} BFS (j); //jump to the farthest array .      } intMain () {inti; scanf ("%d",&N);  for(i=0; i<n;i++) {scanf ("%d",&S[i]); } BFS (0); printf ("%d", CT);//number of steps to print     return 0; } 

Greedy algorithm-Jumping Game II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.