在一个只有0和1的矩阵中,计算只有1存在的最大矩形C#代码
时间: 2023-07-16 16:13:08 浏览: 52
以下是 C# 代码实现:
```
using System;
class MaximalRectangle {
static int MaximalRectangleArea(int[] heights) {
int len = heights.Length;
int[] stack = new int[len + 1];
int idx = 0;
int maxArea = 0;
for (int i = 0; i <= len; i++) {
int h = (i == len ? 0 : heights[i]);
while (idx > 0 && h < heights[stack[idx - 1]]) {
int currHeight = heights[stack[--idx]];
int currWidth = (idx == 0 ? i : i - stack[idx - 1] - 1);
maxArea = Math.Max(maxArea, currHeight * currWidth);
}
stack[idx++] = i;
}
return maxArea;
}
static int MaximalRectangle(char[,] matrix) {
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
int[] heights = new int[cols];
int maxArea = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i, j] == '1') {
heights[j]++;
} else {
heights[j] = 0;
}
}
maxArea = Math.Max(maxArea, MaximalRectangleArea(heights));
}
return maxArea;
}
static void Main(string[] args) {
char[,] matrix = new char[,] {
{'1', '0', '1', '0', '0'},
{'1', '0', '1', '1', '1'},
{'1', '1', '1', '1', '1'},
{'1', '0', '0', '1', '0'}
};
Console.WriteLine(MaximalRectangle(matrix)); // Output: 6
}
}
```
主要思路是利用单调栈计算每一行的最大矩形面积,然后遍历每一行计算最大面积。