【Leetcode】Maximal Square

题目链接:https://leetcode.com/problems/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.

思路:

用c[i][j]表示在长为i、宽为j的矩阵里面,包含matrix[i][j]这个点的最大正方形的长。

显然c[i][j]的大小跟c[i-1][j]、c[i][j-1]、c[i-1][j-1]有关。画图观察c[i-1][j]、c[i][j-1]、c[i-1][j-1]包围起来的面积

可知 c[i][j] = min(c[i-1][j]、c[i][j-1]、c[i-1][j-1]) +1

算法:

public int maximalSquare(char[][] matrix) {  
        if (matrix.length == 0)  
            return 0;  
        int max = 0;  
        int c[][] = new int[matrix.length][matrix[0].length];  
        for (int i = 0; i < matrix.length; i++) {  
            for (int j = 0; j < matrix[0].length; j++) {  
                if (matrix[i][j] == '0') {  
                    continue;  
                }  
                if (i == 0 || j == 0) {// 在边缘时  
                    c[i][j] = 1;  
                } else {  
                    c[i][j] = Math.min(c[i - 1][j - 1], Math.min(c[i - 1][j], c[i][j - 1])) + 1;  
                }  
                max = Math.max(max, c[i][j]);  
            }  
        }  
        return max * max;  
    }  


你可能感兴趣的:(【Leetcode】Maximal Square)