0

I am learning dynamic programming, and I have observed when creating recursive code, sometimes we check out-of-bounds conditions first then check other base cases, and sometimes we check the other bases first and then after that we check the out-of-bound conditions. How do I know which ordering to choose?

For example, a problem could have the conditions ordered like so:

if (i < 0 || j < 0 || i >= matrix.length || j >= matrix[0].length)
{
    return Integer.MAX_VALUE;
}
if (i == matrix.length - 1)
{
    return matrix[i][j];
}

While in other cases, the i == matrix.length - 1 check is put first:

if (i == matrix.length - 1)
{
    return matrix[i][j];
} 
if (i < 0 || j < 0 || i >= matrix.length || j >= matrix[0].length)
{
    return Integer.MAX_VALUE;
}

I am confused when to choose which ordering of conditions to use when solving recursion problems.

1 Answer 1

1

In this specific case, it makes no difference, since the values they check do not overlap.

  • i == matrix.length - 1 checks if i is the last element in the matrix
  • i < 0 || j < 0 || i >= matrix.length || j >= matrix[0].length checks to make sure that i/j are inside the limits of the matrix.

For example, a 4x4 matrix would have a length of 4 for both i and j

  • if (i == matrix.length - 1) would be if (i == 3)
  • if (i < 0 || j < 0 || i >= matrix.length || j >= matrix[0].length) would be if (i < 0 || j < 0 || i >= 4 || j >= 4)

Notice how the first if statement only checks index 3, while the other checks all indices EXCEPT 0-3.


The order of these if statements would only matter if the base case could include out-of-bounds values. For example, if the i == matrix.length - 1 check was instead written to be i >= matrix.length - 1, then it being ordered first would cause the program to index matrix out of bounds.

I'd personally put the out-of-bounds check first since it's clearer to me that it's just a safety check, but that's just opinion.

Not the answer you're looking for? Browse other questions tagged or ask your own question.