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