Maximal Rectangle
Given a 2D binary matrix representing a grid of '0's and '1's, find the largest rectangle containing only '1's and return its area. This problem is a classic in algorithmic challenges and has applications in image processing and data analysis where identifying contiguous regions of interest is crucial.
Problem Description
You are given a 2D matrix where each cell can either be '0' or '1'. Your task is to find the maximum area of a rectangle that can be formed entirely of '1's within this matrix.
Key Requirements:
- Identify all possible rectangles composed solely of '1's.
- Calculate the area of each such rectangle.
- Return the largest area found.
Expected Behavior:
- The function should accept a 2D matrix as input.
- The function should return a single integer representing the maximum area.
Edge Cases:
- An empty matrix.
- A matrix containing only '0's.
- A matrix containing only '1's.
- A matrix with a single row or a single column.
Examples
Example 1:
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6
Explanation: The largest rectangle containing only '1's is formed by the cells at indices (1,2), (1,3), (1,4), (2,2), (2,3), (2,4). This rectangle has a width of 3 and a height of 2, resulting in an area of 6.
Example 2:
Input:
[
["0"]
]
Output: 0
Explanation: The matrix contains no '1's, so no rectangle can be formed.
Example 3:
Input:
[
["1"]
]
Output: 1
Explanation: The matrix contains a single '1', forming a 1x1 rectangle.
Example 4:
Input:
[
["1","1","1"],
["1","1","1"],
["1","1","1"]
]
Output: 9
Explanation: The entire matrix is filled with '1's, forming a 3x3 rectangle with an area of 9.
Constraints
- The number of rows (
M) in the matrix will be between 0 and 200, inclusive. - The number of columns (
N) in the matrix will be between 0 and 200, inclusive. - Each cell in the matrix will contain either '0' or '1'.
- The solution should aim for an efficient time complexity.
Notes
This problem can be approached by iterating through the matrix and, for each cell, considering it as the bottom-right corner of a potential maximal rectangle. A common and efficient strategy involves leveraging a subproblem: finding the largest rectangle in a histogram. Consider each row as the base of a histogram where the height of each bar represents the number of consecutive '1's above it (including the current cell). You can then apply a known algorithm for finding the largest rectangle in a histogram to each row's derived histogram.