-1

I have a question when executing following codes:

if(column!=n-1){
    if(returnValue[row][column+1] == 0) column++;
    else {
        row++;
        direction = "down";
    }
}
else {
    row++;
    direction = "down";
}

If you see the codes, I need to check whether the column is exceeding the boundary first and then do another checking, which have duplicated codes in the else section. Is there a better way to write this logic?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

0

in order to avoid getting out of bounds, you'd have to check if row & column are within the boundaries of the array. I do not expect either value to go below 0 as there is no decrement if your code, so I only checked the length, but not negative indices.

if (row < returnValue.length && column < returnValue[row].length - 1 && returnValue[row][column+1] == 0) column++;
else {
    row++;
    direction = "down";
}
thinkgruen
  • 929
  • 10
  • 15
0

I will give you an example cause sounds similar to a matrix issue , please focus on for loops cause the main key is there:

// JAVA Code for Boundary elements of a Matrix
class GFG {

    public static void printBoundary(int a[][], int m,
                                    int n)
    {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0)
                    System.out.print(a[i][j] + " ");
                else if (i == m - 1)
                    System.out.print(a[i][j] + " ");
                else if (j == 0)
                    System.out.print(a[i][j] + " ");
                else if (j == n - 1)
                    System.out.print(a[i][j] + " ");
                else
                    System.out.print(" ");
            }
            System.out.println("");
        }
    }

    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };

        printBoundary(a, 4, 4);
    }
}
Alva Santi
  • 75
  • 5