
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Largest Rectangle of 1's with Column Swapping in Python
Suppose we have a binary matrix, we have to find the largest rectangle of all 1's in that given matrix. The rectangle can be built by swapping or exchanging any pair of columns of that matrix.
So, if the input is like
1 | 0 | 0 | 1 | 0 |
1 | 0 | 0 | 1 | 1 |
1 | 1 | 0 | 1 | 0 |
then the output will be the 6 in this case. The rectangle can be generating by exchanging column 1 with 3. The matrix after exchanging will be −
0 | 0 | 1 | 1 | 0 |
0 | 0 | 1 | 1 | 1 |
1 | 0 | 1 | 1 | 0 |
To solve this, we will follow these steps −
row := size of mat
col := size of mat[0]
temp := a matrix of order (row + 1) x (col + 1), and fill with 0
-
for i in range 0 to col, do
temp[0, i] := mat[0, i]
-
for j in range 1 to row, do
-
if mat[j, i] is same as 0, then
temp[j, i] := 0
-
otherwise,
temp[j, i] := temp[j - 1, i] + 1
-
-
for i in range 0 to row, do
cnt := an array of size (row + 1), and filled with 0
-
for j in range 0 to col, increase by 1, do
cnt[temp[i, j]] := cnt[temp[i, j]] + 1
col_no := 0
j := row
-
while j >= 0, do
-
if cnt[j] > 0, then
-
for k in range 0 to cnt[j], do
temp[i, col_no] := j
col_no := col_no + 1
-
j := j - 1
-
area_maximum := 0
-
for i in range 0 to row, do
-
for j in range 0 to col, do
area_current :=(j + 1) * temp[i, j]
-
if area_current > area_maximum, then
area_maximum := area_current
-
return area_maximum
Example
Let us see the following implementation to get better understanding −
def maxArea(mat): row = len(mat) col = len(mat[0]) temp = [[0 for i in range(col + 1)] for i in range(row + 1)] for i in range(0, col): temp[0][i] = mat[0][i] for j in range(1, row): if ((mat[j][i] == 0)): temp[j][i] = 0 else: temp[j][i] = temp[j - 1][i] + 1 for i in range(0, row): cnt = [0 for i in range(row + 1)] for j in range(0, col, 1): cnt[temp[i][j]] += 1 col_no = 0 j = row while(j >= 0): if (cnt[j] > 0): for k in range(0, cnt[j]): temp[i][col_no] = j col_no += 1 j -= 1 area_maximum = 0 for i in range(0, row): for j in range(0, col): area_current = (j + 1) * temp[i][j] if (area_current > area_maximum): area_maximum = area_current return area_maximum mat = [ [0, 0, 1, 1, 0], [0, 0, 1, 1, 1], [1, 0, 1, 1, 0]] print("Area : ",maxArea(mat))
Input
[ [1, 0, 0, 1, 0], [1, 0, 0, 1, 1], [1, 1, 0, 1, 0]]
Output
Area : 2