[LeetCode-JAVA] Contains Duplicate IIIMaximal 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.

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.

 

思路:动态规划,逐步保存节点处能达到的最优值,为了方便存储以该点为右下角的矩形内,满足条件的 最大的正方形的边长。

当循环到 matrix[i][j]时候,如果该处的char值为1,则状态转移方程为 dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;

 

代码:

public class Solution {
    public int maximalSquare(char[][] matrix) {
        int m = matrix.length;
        if(m == 0) return 0;
        int n = matrix[0].length;
        
        int[][] dp = new int[m][n];
        
        int area = 0;
        for(int i = 0 ; i < m ; i++){
            for(int j = 0 ; j < n ; j ++){
                dp[i][j] = matrix[i][j] - '0';
                if(i-1 >= 0 && j-1 >=0 && dp[i][j] > 0){
                    dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;
                }
                if(dp[i][j] > area)
                    area = dp[i][j];
            }
        }
        
        return area*area;
    }
}

 

你可能感兴趣的:(LeetCode)