题目
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.
也就是返回最大数组的行乘以列。
我的方法
想法很简单,就是计算从当前位置向右下角范围内的最大的“1”数组,所以问题也很明显,算法不够快,超出限定时间。。
public class Solution {
public int MaximalRectangle(char[,] matrix)
{
int row = matrix.GetLength(0);
int column = matrix.GetLength(1);
int max = 0;
for (int locationX = 0; locationX < row; locationX++)
{
for (int locationY = 0; locationY < column; locationY++)
{
for (int m = 1; m <= row - locationX; m++)
{
for (int n = 1; n <= column - locationY; n++)
{
if (MaxRectangleIn(locationX, locationY, m, n, matrix))
max = max > m * n ? max : m * n;
else
break;
}
}
}
}
return max;
}
private bool MaxRectangleIn(int locationX, int locationY,int height,int width, char[,] matrix)
{
char[,] temp = new char[height, width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (matrix[locationX + i, locationY + j] == '0') return false;
}
}
return true;
}
}
好的方法
它针对每一行计算当前行以及之前行的“1”数组最大值,分析数组并计算”left”,”right”和“height”存在dp数组里。至于它为什么要计算这三个量,我实在看不懂。。
public int MaximalRectangle(char[,] matrix) {
int n = matrix.GetLength(1), maxA = 0;
int[,] dp = new int[n, 3]; //[i, 0] is left; [i, 1] is right; [i, 2] is height
for(int i = 0; i < n; i++) dp[i, 1] = n;
for(int i = 0; i < matrix.GetLength(0); i++) {
int cur_left = 0, cur_right = n;
for(int j = 0; j < n; j++) {
if(matrix[i, j] == '1') // compute height (can do this from either side)
dp[j, 2]++;
else dp[j, 2]=0;
if(matrix[i, j] == '1') // compute left (from left to right)
dp[j, 0] = Math.Max(dp[j, 0], cur_left);
else { dp[j, 0] = 0; cur_left = j + 1; }
}
// compute right (from right to left)
for(int j = n - 1; j >= 0; j--) {
if(matrix[i, j] == '1') dp[j, 1] = Math.Min(dp[j, 1], cur_right);
else { dp[j, 1] = n; cur_right = j; }
}
// compute the area of rectangle (can do this from either side)
for(int j = 0; j < n; j++)
maxA = Math.Max(maxA, (dp[j, 1] - dp[j, 0]) * dp[j, 2]);
}
return maxA;
}