Maximal Square

题目地址:
https://leetcode.com/problems/maximal-square/#/description

题目:
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 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.

解题思路:
这道题用dynamic programming就可以来解决。

代码:

public int maximalSquare(char[][] matrix) {
    if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
        return 0;
    }

    int m = matrix.length, n = matrix[0].length;
    int max = 0;
    int[][] dp = new int[m][n];
    for(int i = 0; i < m; i++){
        dp[i][0] = matrix[i][0] - '0';
        max = Math.max(dp[i][0], max);
    }

    for(int j = 0; j < n; j++){
        dp[0][j] = matrix[0][j] - '0';
        max = Math.max(dp[0][j], max);
    }
    for(int i = 1; i <= m - 1; i++){
        for(int j = 1; j <= n - 1; j++){
            if(matrix[i][j] == '0'){
                dp[i][j] = 0;
            }
            else{
                int left = dp[i][j - 1];
                int right = dp[i - 1][j];
                if(left == right){
                    dp[i][j] = matrix[i - left][j - right] == '1' ? left + 1 : left;
                }
                else{
                    dp[i][j] = Math.min(left, right) + 1;
                }
            }
            max = Math.max(max, dp[i][j]);
        }
    }
    return max * max;
}




Comments

Popular Posts