|
| 1 | +package me.ramswaroop.dynamicprogramming; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by IntelliJ IDEA. |
| 5 | + * |
| 6 | + * @author: ramswaroop |
| 7 | + * @date: 9/20/15 |
| 8 | + * @time: 1:18 PM |
| 9 | + */ |
| 10 | +public class MinimumJumpsToReachEnd { |
| 11 | + |
| 12 | + /** |
| 13 | + * Given an array of integers where each element represents the max number of steps that |
| 14 | + * can be made forward from that element. Write a function to return the minimum number |
| 15 | + * of jumps to reach the end of the array (starting from the first element). If an element |
| 16 | + * is 0, then we cannot move through that element. |
| 17 | + * |
| 18 | + * A naive approach is to start from the first element and recursively call for all the elements |
| 19 | + * reachable from first element. The minimum number of jumps to reach end from first can be calculated |
| 20 | + * using minimum number of jumps needed to reach end from the elements reachable from first. |
| 21 | + * |
| 22 | + * minJumps(start, end) = Min ( minJumps(k, end) ) for all k reachable from start |
| 23 | + * |
| 24 | + * @param a |
| 25 | + * @param l |
| 26 | + * @param h |
| 27 | + * @return |
| 28 | + */ |
| 29 | + public static int getMinimumJumpsToReachEndNaive(int[] a, int l, int h) { |
| 30 | + // base cases |
| 31 | + if (l == h) return 0; |
| 32 | + if (a[l] == 0) return Integer.MAX_VALUE; |
| 33 | + |
| 34 | + int minJumps = Integer.MAX_VALUE; |
| 35 | + for (int i = l + 1; i <= h && i <= a[l] + l; i++) { |
| 36 | + int jumps = getMinimumJumpsToReachEndNaive(a, i, h); |
| 37 | + if (jumps + 1 < minJumps) { |
| 38 | + minJumps = jumps + 1; |
| 39 | + } |
| 40 | + } |
| 41 | + return minJumps; |
| 42 | + } |
| 43 | + |
| 44 | + public static void main(String a[]) { |
| 45 | + int[] ar = new int[]{1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9}; |
| 46 | + System.out.println(getMinimumJumpsToReachEndNaive(ar, 0, ar.length - 1)); |
| 47 | + ar = new int[]{5, 4, 3, 2, 1}; |
| 48 | + System.out.println(getMinimumJumpsToReachEndNaive(ar, 0, ar.length - 1)); |
| 49 | + ar = new int[]{1, 2, 3, 4, 5}; |
| 50 | + System.out.println(getMinimumJumpsToReachEndNaive(ar, 0, ar.length - 1)); |
| 51 | + ar = new int[]{1, 2}; |
| 52 | + System.out.println(getMinimumJumpsToReachEndNaive(ar, 0, ar.length - 1)); |
| 53 | + } |
| 54 | +} |
0 commit comments