最大正方形
题目
在一个二维01矩阵中找到全为1的最大正方形
样例
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
返回 4题解
定义相同大小的辅助数组res,且第一例和第一行元素与原数组相同。从res[1][1]开始,如果原数组matrix[i][j]为0则表示当前点不存在正方形,即边长为0。如果matrix[i][j]为1则表示至少存在边长为1的正方形,此时考量res[i][j]的左元素,左上角元素和上面的元素,取最小边长+1最为res[i][j]的边长。保存最大边长,最后再返回面积即可。
public class Solution {
/**
* @param matrix: a matrix of 0 and 1
* @return: an integer
*/
public int maxSquare(int[][] matrix) {
int ans = 0;
int n = matrix.length;
int m;
if(n > 0)
{
m = matrix[0].length;
}
else
{
return ans;
}
int [][]res = new int [n][m];
for(int i = 0; i < n; i++)
{
res[i][0] = matrix[i][0];
ans = Math.max(res[i][0] , ans);
for(int j = 1; j < m; j++)
{
if(i > 0)
{
if(matrix[i][j] > 0)
{
res[i][j] = Math.min(res[i - 1][j],Math.min(res[i][j-1], res[i-1][j-1])) + 1;
}
else
{
res[i][j] = 0;
}
}
else
{
res[i][j] = matrix[i][j];
}
ans = Math.max(res[i][j], ans);
}
}
return ans*ans;
}
}
Last Update 2016.11.19