leetCode No.221 Maximal Square

题目

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
相似问题: (H) Maximal Rectangle

题意

给定一个由01组成的二位矩阵,寻找其中由1组成的最大的正方形并返回其面积。

解题思路

初始化矩阵后,遍历当前矩阵的点,若当前点为1,则以当前点为右下角点。由此可得递推公式:f(x,y) = min(f(x-1)(y),f(x)(y-1),f(x-1)(y-1)) + 1。

代码

public class Solution {
    public int maximalSquare(char[][] matrix) {
        if (matrix.length == 0) {
            return 0;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int[][] ret = new int[row][col];
        int max = 0;
        // 初始化列
        for (int i = 0; i < row; i++) {
            if (matrix[i][0] == '1') {
                ret[i][0] = 1;
                max = 1;
            }
        }
        // 初始化行
        for (int i = 0; i < col; i++) {
            if (matrix[0][i] == '1') {
                ret[0][i] = 1;
                max = 1;
            }
        }
        //递推公式:f(x,y) = min(f(x-1)(y),f(x)(y-1),f(x-1)(y-1)) + 1
        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++) {
                if (matrix[i][j] == '0') {
                    ret[i][j] = 0;
                }else {
                    ret[i][j] = Math.min(ret[i - 1][j], Math.min(ret[i][j - 1], ret[i - 1][j - 1])) + 1;
                    max = Math.max(max, ret[i][j]);
                }
            }
        }
        return max * max;
    }
}

相关链接

源代码(github)
原题

你可能感兴趣的:(LeetCode)