Given a binary matrix, find the maximum size rectangle binary-sub-matrix with all 1’s.
Input : 0 1 1 0 1 1 1 1 1 1 1 1 1 1 0 0 Output : 1 1 1 1 1 1 1 1
We have discussed a dynamic programming based solution for finding largest square with 1s.
In this post an interesting method is discussed that uses largest rectangle under histogram as a subroutine. Below are steps. The idea is to update each column of a given row with corresponding column of previous row and find largest histogram area for for that row.
Step 1: Find maximum area for row Step 2: for each row in 1 to N - 1 for each column in that row if A[row][column] == 1 update A[row][column] with A[row][column] += A[row - 1][column] find area for that row and update maximum area so far
step 1: 0 1 1 0 maximum area = 2 step 2: row 1 1 2 2 1 area = 4, maximum area becomes 4 row 2 2 3 3 2 area = 8, maximum area becomes 8 row 3 3 4 0 0 area = 6, maximum area remains 8
Below is the implementation. It is strongly recommended to refer this post first as most of the code taken from there.
Area of maximum rectangle is 8
Time Complexity : O(R x X)
This article is contributed by Sanjiv Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Find the number of rectangles of size 2*1 which can be placed inside a rectangle of size n*m
- Check whether row or column swaps produce maximum size binary sub-matrix with all 1s
- Maximum value in a matrix which contain intersecting concentric submatrix
- Maximize the binary matrix by filpping submatrix once
- Maximum subarray size, such that all subarrays of that size have sum less than k
- Sliding Window Maximum (Maximum of all subarrays of size k)
- Maximum sum rectangle in a 2D matrix | DP-27
- Maximum area of rectangle possible with given perimeter
- Rectangle with Maximum Area using Java Pair
- Number of squares of maximum area in a rectangle
- Find if there is a rectangle in binary matrix with corners as 1
- Maximum area rectangle by picking four sides from array
- Length and Breadth of rectangle such that ratio of Area to diagonal^2 is maximum
- Maximum size subset with given sum
- Subsequence of size k with maximum possible GCD