Program to find largest submatrix with rearrangements in Python

PythonServer Side ProgrammingProgramming

Suppose we have an m x n binary matrix, we can rearrange the columns of the matrix in any order. We have to find the area of the largest submatrix within matrix where every element of the submatrix is 1 after performing some reordering task.

So, if the input is like

101
111
001

then the output will be 4 because, after column swapping we are getting matrix like

110
111
010

here maximum submatrix is of square sized with four 1's.

To solve this, we will follow these steps −

  • row := number of rows of matrix, col := number of columns of matrix
  • for j in range 0 to col - 1, do
    • for i in range 1 to row - 1, do
      • if matrix[i, j] is 1, then
        • matrix[i, j] := matrix[i, j] + matrix[i-1, j]
  • ans := 0
  • for i in range 0 to row - 1, do
    • sort the list matrix[i]
    • for j in range col-1 to 0, decrease by 1, do
      • if matrix[i, j] is same as 0, then
        • come out from the loop
        • ans = maximum of ans and (col-j)*matrix[i, j])
  • return ans

Example

Let us see the following implementation to get better understanding −

def solve(matrix):
   row, col = len(matrix), len(matrix[0])
   for j in range(col):
      for i in range(1,row):
         if matrix[i][j]:
            matrix[i][j]+=matrix[i-1][j]
   ans = 0
   for i in range(row):
      matrix[i].sort()
      for j in range(col-1,-1,-1):
         if matrix[i][j]==0:
            break
         ans = max(ans, (col-j)*matrix[i][j])
   return ans

matrix = [[0,0,1],[1,1,1],[1,0,1]]
print(solve(matrix))

Input

[[0,0,1],[1,1,1],[1,0,1]]

Output

4
raja
Updated on 06-Oct-2021 13:39:57

Advertisements