Greedy Algorithm-Skip Game 2, greedy algorithm skip
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 at that position.
Your goal is to reach the last subscript and use the minimum number of hops.
For example:
A = [2, 3, 4]. The minimum number of jumps to the last target is 2. (Skip step 1, from subscript 0 to 1, then jump step 3 to reach the last subscript. Two times in total)
Input Format
Enter A positive integer n (1 ≤ n ≤ 100) in the first row, and then n integers in the next row, indicating array.
Output Format
Finally, the minimum number of hops is output.
Sample Input
53 1 1 1 1
Sample output
2
Analysis:
Based on the analysis in the example above, similar to the greedy algorithm, after each step jump, the number of steps cnt ++, and then determine the farthest distance from the next hop until it reaches s [n-1], as shown in:
The Code is as follows:
# Include <stdio. h> int n, s [10000] = {0}, ct = 0; int bfs (int I) {int k, j = 0, l, max = 0; if (I> = N-1) return 0; // find and Exit k = s [I]; ct ++; if (I + k> = N-1) return 0; // find and exit for (l = I + 1; l <= I + k; l ++) // () find the farthest distance {if (max <= l + s [l]) that can be jumped to next time // update data {j = l; max = l + s [l] ;}} bfs (j); // jump to the farthest array} int main () {int I; scanf ("% d", & n); for (I = 0; I <n; I ++) {scanf ("% d", & s [I]);} bfs (0); printf ("% d", ct ); // print the number of steps return 0 ;}