`

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.

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.

典型的二维动态规划的问题。我们构造一个二维的dp数组,dp[i][j]代表到点(i , j)时由1构成的正方形的最大长度。当char[i][j] 为0时,dp[i][j]在当前点只能为0;如果char[i][j]为1时,dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1,我们只能选择一个最小的正方形,然后加1,每次都用一个max来记录当前的最大值。最后返回max * max即可。代码如下:
public class Solution {
    public int maximalSquare(char[][] matrix) {
        if(matrix == null || matrix.length == 0) return 0;
        int m = matrix.length;
        int n = matrix[0].length;
        int max = 0;
        int[][] dp = new int[m][n];
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(i == 0 || j == 0) {
                    dp[i][j] = matrix[i][j] - '0';
                } else if(matrix[i][j] == '0') {
                    dp[i][j] = 0;
                } else {
                    dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;
                }
                if(dp[i][j] > max) max = dp[i][j];
            }
        }
        return max * max;
    }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics