Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.
For example, given the following matrix:
1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
Return 4.
这是一道非常简单的动态规划的题,每一个点只考虑所在位置(i,j)的左上方能构成的最大方阵。
用一个二维数组记录每个点的最大方阵数(开根号后的值),
点(i,j)最大方阵数开根号后的值=点(i-1,j)、点(i,j-1)、点(i-1,j-1)中最小的那个最大方阵数开根号后的值
public int MaximalSquare(char[,] matrix)
{
int m = (int)matrix.GetLongLength(0);
int n = (int)matrix.GetLongLength(1);
if (m * n == 0)
return 0;
int[,] count = new int[m+1, n+1];
int tmp,max=0;
for (int i = 1; i < m+1; i++)
{
for (int j = 1; j < n+1; j++)
{
if (matrix[i-1, j-1] != '0')
{
tmp = count[i - 1, j] < count[i, j - 1] ? count[i - 1, j] : count[i, j - 1];
tmp= count[i - 1, j-1] < tmp ? count[i - 1, j - 1] : tmp;
count[i, j] = tmp + 1;
if (tmp + 1 > max)
max = tmp + 1;
}
}
}
return max*max;
}