Javatpoint Logo
Javatpoint Logo

Maximum Size Square Sub-matrix with all 1s

The Maximum Size Square Sub-matrix with all 1s problem is a classic dynamic programming problem. The goal is to find the largest square sub-matrix that contains only 1s in a given matrix of 0s and 1s.

Algorithm:

Create a new matrix of the same size as the input matrix to store the results. Let's call this matrix dp.

Initialize the first row and the first column of the dp matrix with the same values as the input matrix.

For each cell (i, j) in the input matrix starting from (1, 1):

  1. If the cell in the input matrix is 1, set dp[i][j] to the minimum value of the cells above, to the left, and diagonally above-left to (i, j). Then, increment dp[i][j] by 1.
  2. If the cell in the input matrix is 0, set dp[i][j] to 0, as a square cannot be formed with a 0.

Find the maximum value in the dp matrix. The square of this value represents the size of the largest square sub-matrix with all 1s.

Java code:

Output:

Inplace MxN size matrix transpose

Explanation:

  • The findMaxSquareSubMatrix function takes a 2D matrix as input and returns the size of the maximum square sub-matrix with all 1s.
  • The dp matrix is used to store the results. It has the same dimensions as the input matrix.
  • The function initializes the first row and the first column of the dp matrix with the values of the input matrix since they don't have any dependencies on previous rows or columns.
  • The nested loop iterates through the remaining cells (excluding the first row and first column) of the dp matrix and calculates the size of the largest square sub-matrix that can be formed ending at that cell.
  • If the cell in the input matrix is 1, the function sets the value of dp[i][j] to the minimum value of the cells above, to the left, and diagonally above-left to (i, j). It then increments the value by 1 to represent the current cell's contribution to the size of the square sub-matrix.
  • If the cell in the input matrix is 0, the function sets dp[i][j] to 0 since a square sub-matrix cannot be formed with a 0.
  • While calculating the dp matrix, the function keeps track of the maximum value found so far, which represents the size of the largest square sub-matrix with all 1s.
  • The function finally returns the square of the maximum value found, which gives the size of the largest square sub-matrix.

Time Complexity: O(rows*cols) //where "rows" is the number of rows in the input matrix and "cols" is the number of columns in the input matrix.

Space Complexity: O(rows*cols) // for dp array







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