Search code examples
javarecursiondynamic-programming

Why is this code giving me out of bound error?


public static int helper(int r, int c, int[][] dp) {
    if (r == 1 || c == 1)
        return dp[r][c] = 1;
    if (dp[r][c] == 0) {
        dp[r][c] = helper(r - 1, c, dp) + helper(r, c - 1, dp);
    }
    return dp[r][c];
}

public static int count(int r, int c) {
    int dp[][] = new int[r][c];
    for(int i =0; i<r ;i++){
        for(int j = 0; j<c;j++){
            dp[i][j] = 0;
        }
    }
    int ans = helper(r, c, dp);
    return ans;
}

when i didnt use the helper function it worked fine but doing like this it gives an error - Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

//updated public class maze {

public static int count(int r, int c, int[][] dp) {
    if (r == 1 || c == 1)
        return dp[r][c] = 1;
    if (dp[r][c] == 0) {
        dp[r][c] = count(r - 1, c, dp) + count(r, c - 1, dp);
    }
    return dp[r][c];
}

public static void main(String[] args) {
    int dp[][] = new int[4][4];
    for (int i = 0; i < dp.length; i++) {
        for (int j = 0; j < dp.length; j++) {
            dp[i][j] = 0;
        }
    }
    System.out.println(count(1, 1, dp));
    System.out.println(count(2, 3, dp));
    System.out.println(count(3, 2, dp));
    System.out.println(count(3, 3, dp));
    // System.out.println(count(18, 18, dp));

}

}

//this code will now work except for the larger input i.e (18 , 18)


Solution

  • Following condition should have a check that your r - 1 or c- 1 does not go below 0

        if (dp[r][c] == 0) {
            dp[r][c] = helper(r - 1, c, dp) + helper(r, c - 1, dp);
        }
    

    Also when calling helper from count reduce the values by 1 so that it points to last index and not outside as pointed out by @hfontanez