Javatpoint Logo
Javatpoint Logo

Find the Good Matrix Problem in Java

Given a 2-dimensional array ARR with N rows and M columns, where each element contains a value of 0 or 1, convert the given matrix into a Good matrix. In a Good matrix, if an element is 0, all elements in its row and column should also be 0.

For example, if arr is the following matrix:

Find the Good Matrix Problem in Java

Input Format:

The first line of the input contains an integer, T, denoting the number of test cases. For each test case, the first line contains two integers, N and M, denoting the number of rows and columns in the array. The next N lines of each test case contain M space-separated integers denoting the elements of the array arr.

Find the Good Matrix Problem in Java

Output Format:

For each test case, return the updated matrix after updating the given matrix as described in the problem statement.

Algorithm

  1. Make a two-dimensional array called "the answer" that has N rows and M columns.
  2. Copy all elements from the matrix arr to the array answer.
  3. Iterate over each element in the matrix arr.
    • If the element ARR[row][col] is equal to 0, perform the following:
      • Set all elements in the entire row to 0 by iterating over the index from 0 to N-1 and setting answer[index][col] to 0.
      • Set all elements in the entire column to 0 by iterating over the index from 0 to M-1 and setting answer[row][index] to 0.
  4. Return the matrix answer.
  5. End the program.

Implementation:

Filename: GoodMatrix.java

Output:

0 1 1 0 
0 0 0 0 
0 1 1 0 
0 0 0 0

Complexity Analysis:

Time Complexity: The code iterates over each element in the given matrix, resulting in nested loops. The outer loop iterates 'row' from 0 to 'n - 1', where 'n' is the number of rows. Where'm' is the number of columns, the inner loop iterates 'col' from 0 to'm - 1'. Within the nested loops, there are additional loops for setting the row and column values to 0. As a result, the time complexity is denoted by the notation O(n * m * (n + m)), where n denotes the number of rows and m the number of columns.

Space Complexity: The code creates a new 2-dimensional array 'answer' to store the modified matrix. The space required for the 'answer' array is the same as the input matrix: ' n' rows and 'm' columns. Therefore, the space complexity is O(n * m).







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA