最大矩形
难度:困难
题目描述
给定一个仅包含 0
和 1
、大小为 rows x cols
的二维二进制矩阵,找出只包含 1
的最大矩形,并返回其面积。
示例1
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:6
示例2
输入:matrix = []
输出:0
示例3
输入:matrix = [["0"]]
输出:0
示例4
输入:matrix = [["1"]]
输出:1
示例5
输入:matrix = [["0","0"]]
输出:0
题解
是0084的进阶,可以将它升维转换为二维数组,具体如下
比如matrix = [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“1”],[“1”,“0”,“0”,“1”,“0”]]
可以转换为:
4 0 3 0 0
3 0 2 3 2
2 1 1 2 1
1 0 0 1 0
即:将需要讨论的内容缩小,将本来需要讨论的纵坐标转化为每一行的高,之后就可以根据0084的算法来对每一行的内容都取最大面积,之后对结果进行对比,最大的数即为结果
想法代码
class Solution
{
public static void Main(String[] args)
{
char[][] matrix =
{
new[] { '1', '0', '1', '0', '0' },
new[] { '1', '0', '1', '1', '1' },
new[] { '1', '1', '1', '1', '1' },
new[] { '1', '0', '0', '1', '0' }
};
Solution solution = new Solution();
int ans = solution.MaximalRectangle(matrix);
Console.WriteLine(ans);
}
public int MaximalRectangle(char[][] matrix)
{
int maxArea = 0;
int rows = matrix.Length;
int cols = matrix[0].Length;
int[] heights = new int[cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (matrix[i][j] == '0')
{
heights[j] = 0;
}
else
{
heights[j]++;
}
}
maxArea = Math.Max(maxArea, GetMaxArea(heights));
}
return maxArea;
}
public int GetMaxArea(int[] heights)
{
int[] left = new int[heights.Length];
int[] right = new int[heights.Length];
Array.Fill(left, -1);
Array.Fill(right, heights.Length);
Stack<int> stack = new Stack<int>();
for (int i = 0; i < heights.Length; i++)
{
int height = heights[i];
while (stack.Count > 0 && heights[stack.Peek()] >= height)
{
right[stack.Pop()] = i;
}
if (stack.Count > 0)
{
left[i] = stack.Peek();
}
stack.Push(i);
}
int ans = 0;
for (int i = 0; i < heights.Length; i++)
{
ans = Math.Max(ans, (right[i] - left[i] - 1) * heights[i]);
}
return ans;
}
}