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.