![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find largest submatrix with rearrangements in Python
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
1 | 0 | 1 |
1 | 1 | 1 |
0 | 0 | 1 |
then the output will be 4 because, after column swapping we are getting matrix like
1 | 1 | 0 |
1 | 1 | 1 |
0 | 1 | 0 |
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]
- if matrix[i, j] is 1, then
- for i in range 1 to row - 1, do
- 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])
- if matrix[i, j] is same as 0, then
- 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
Advertisements