Oscar Anthony
Oscar Anthony

Reputation: 190

Fill a Matrix (2d array) recursively in Java

I have a Java programming assignment to do and in one of the questions, I have to fill a boolean 2d array (matrix) with "false" everywhere. I did it using two loops as following:

// The length and width are given

boolean [][] matrix; 
matrix = new boolean [length][width];

int row;
int col;

for (row = 0; row < length; row++)
{
   for (col = 0; col < width; col++)
   {
      matrix[row][col] = false;
   }
} 

The thing is that we just started the recursion chapter, and I would like if there is a way to do the same thing but this time using only recursion... Thank you!

Upvotes: 0

Views: 8891

Answers (2)

Radiodef
Radiodef

Reputation: 37845

You can mimic the nested loop structure with recursion:

public static void fillWithFalse(boolean[][] array, int row) {
    if (row < array.length) {
        fillWithFalse(array[row], 0);
        fillWithFalse(array, row + 1);
    }
}

public static void fillWithFalse(boolean[] array, int col) {
    if (col < array.length) {
        array[col] = false;
        fillWithFalse(array, col + 1);
    }
}

or

public static void fillWithFalse(boolean[][] array, int row, int col) {
    if (row < array.length) {
        if (col < array[row].length) {
            array[row][col] = false;
            fillWithFalse(array, row, col + 1);
        } else {
            fillWithFalse(array, row + 1, 0);
        }
    }
}

Which is identical logic. But recursion is not good for this kind of thing and also to fill an array with false the correct solution is this:

boolean[][] matrix = new boolean[length][width];

Because boolean arrays will be default initialized with all elements as false. If the assignment is literally to fill a boolean array with false it may be basically a trick question because no action is necessary except to instantiate the array.

Upvotes: 3

nonamer92
nonamer92

Reputation: 1917

Well, not sure why is it necessary.. but.. here's my solution:

public static void insertFalse(boolean [][] arr,int row,int column)
{
    if(row == 0&&column==0)
        return ;
    arr[row][column] = false;
    if(column == 0)
          insertFalse(arr,row-1,arr[0].length-1);
    else
        insertFalse(arr, row, column-1);
}

Upvotes: 0

Related Questions