Maximal Square

Maximal Square

问题:

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.

思路:

  动态规划

我的代码:

public class Solution {
    public int maximalSquare(char[][] matrix) {
        if(matrix==null || matrix.length==0 || matrix[0].length==0) return 0;
        int row = matrix.length;
        int col = matrix[0].length;
        int max = 0;
        int[][] square = new int[row][col];
        //first row
        for(int i=0; i<row; i++)
            square[i][0] = matrix[i][0]-'0';
        //first col
        for(int j=0; j<col; j++)
            square[0][j] = matrix[0][j]-'0';
        for(int i=1; i<row; i++)
        {
            for(int j=1; j<col; j++)
            {
                if(matrix[i][j] == '0')     square[i][j] = 0;
                else    square[i][j] = Math.min(Math.min(square[i-1][j], square[i][j-1]), square[i-1][j-1])+1;
            }
        }
        for(int i=0; i<row; i++)
        {
            for(int j=0; j<col; j++)
            {
                max = Math.max(max, square[i][j]);
            }
        }
        
        return max*max;
    }
}
View Code

学习之处:

  • 对于矩形的动态规划问题,往往可以做的是考虑left,up,left-up三个点,看看能推出什么样的递推式
  • 最近写代码,有点懒的想,直接看答案了,这种态度不对,多想,少写才是王道,其实自己想一想是可以做出来的。
  • 改变自己不好的习惯
原文地址:https://www.cnblogs.com/sunshisonghit/p/4551166.html