2

题目:
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.

解答:
第一眼看这道题以为是个搜索问题,所以用dfs解了一下发现边界并没有办法很好地限定成一个square,所以就放弃了这个解法。

可行的解法是很巧妙的:以这个square的最右下角的位置作为存储点f(i, j),当matrix(i, j)是1的时候,f(i, j) = min{f(i - 1, j - 1), f(i - 1, j), f(i, j -1)}. 这是因为如果这是一个square,那么构成这个square的最基本条件就是跟它相邻的边的最小所在square.所以一个square的f值如下:
1 1 1 1 : 1 1 1 1
1 1 1 1 : 1 2 2 2
1 1 1 1 : 1 2 3 3
1 1 1 1 : 1 2 3 4

1 1 0 1 : 1 1 0 1
1 1 1 1 : 1 2 1 1
1 1 1 0 : 1 2 2 0
1 1 1 0 : 1 2 3 0

所以程序如下:

public class Solution {
    //State: f[i][j] is max length of matrix until (i, j);
    //Function: f[i][j] = min(f[i - 1][j - 1], f[i][j - 1], f[i - 1][j]) + 1 if matrix[i - 1][j - 1] == '1';
    //Initialize: f[0][0] = 0;
    //Result: f[matrix.length][matrix[0].length];
    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[][] f = new int[m + 1][n + 1];
        int max = 0;
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (matrix[i - 1][j - 1] == '1') {
                    f[i][j] = Math.min(f[i - 1][j - 1], Math.min(f[i][j - 1], f[i - 1][j])) + 1;
                    max = Math.max(max, f[i][j]);
                }
            }
        }
        
        return max * max;
    }
}

guoluona
199 声望14 粉丝

下一篇 »
174. Dungeon Game