题目描述:算法
在一个二维01矩阵中找到全为1的最大正方形;spa
1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
返回 4;code
算法分析:blog
对于给定矩阵matrix[][],能够创建对应的矩阵DP[][],用DP[i][j]来记录以点i,j为右下角的全1矩阵的最大边长。同时通过分析能够得出,DP[i][j]的值与DP[i-1][j],DP[i][j-1],DP[i-1][j-1]这三者的值有关:it
①若DP[i-1][j],DP[i][j-1],DP[i-1][j-1]三者中存在0值,则DP[i][j]必定为0;io
②若DP[i-1][j],DP[i][j-1],DP[i-1][j-1]均不为0,则DP[i][j]为三者中的最小值+1,由于三者中的最小值必定为三者所共有的不含0的部分,不然会形成缺角;class
所以对于某一点(i,j), 若matrix[i][j]=1,则动态规划表达式为DP[i][j] = min{DP[i-1][j],DP[i][j-1],DP[i-1][j-1]} + 1;di
代码:动态规划
public class Solution { /* * @param matrix: a matrix of 0 and 1 * @return: an integer */ public int maxSquare(int[][] matrix) { // write your code here if(matrix==null){ return 0; } int m = matrix.length; int n = matrix[0].length; int res = 0; int[][] result = new int[m][n]; //矩阵初始化 for(int i=0;i<m;i++){ result[i][0] = matrix[i][0]; res = Math.max(matrix[i][0],res); } for(int j=0;j<n;j++){ result[0][j] = matrix[0][j]; res = Math.max(matrix[0][j],res); } for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ if(matrix[i][j]==1){ result[i][j] = Math.min(result[i-1][j],Math.min(result[i][j-1],result[i-1][j-1]))+1; } res = Math.max(res,result[i][j]); } } return res*res; } }