您的位置:首页 > 其它

LeetCode 221 Maximal Square

2015-12-11 08:41 309 查看

题目描述

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:

[code]1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0


Return 4.

Credits:

Special thanks to @Freezen for adding this problem and creating all test cases.

分析

动态规划,设dp[x][y]是当前matrix[x][y]最大的正方形的长。

dp[x][y]=1+min⎧⎩⎨dp[x−1][y]dp[x][y−1]dp[x−1][y−1] dp[x][y]=1 + min\begin{cases}dp[x-1][y]\\dp[x][y-1]\\dp[x-1][y-1]\end{cases}

代码

[code]    public int maximalSquare(char[][] matrix) {

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

        int mx = matrix.length;
        int my = matrix[0].length;

        int[][] dp = new int[mx][my];
        int max = 0;

        // 初始化第0行
        for (int i = 0; i < my; i++) {
            if (matrix[0][i] == '1') {
                dp[0][i] = 1;
                max = 1;
            }
        }

        // 初始化第0列
        for (int i = 1; i < mx; i++) {
            if (matrix[i][0] == '1') {
                dp[i][0] = 1;
                max = 1;
            }
        }

        // dp[x][y] = min(dp[x-1][y], dp[x][y-1], dp[x-1][y-1]) + 1
        for (int x = 1; x < mx; x++) {
            for (int y = 1; y < my; y++) {

                if (matrix[x][y] == '1') {
                    dp[x][y] = Math.min(Math.min(dp[x - 1][y], dp[x][y - 1]),
                            dp[x - 1][y - 1]) + 1;
                    max = Math.max(max, dp[x][y]);
                }

            }
        }

        return max * max;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: