Maximal Square

Posted flagyuri

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Maximal Square相关的知识,希望对你有一定的参考价值。

Description

Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest square containing all 1‘s and return its area.

Example

Example 1:

Input:
[
  [1, 0, 1, 0, 0],
  [1, 0, 1, 1, 1],
  [1, 1, 1, 1, 1],
  [1, 0, 0, 1, 0]
]
Output: 4

Example 2:

Input:
[
  [0, 0, 0],
  [1, 1, 1]
]
Output: 1
思路:

可以归类为动态规划题目, 推荐用递推来实现.

设定状态: dp[i][j] 表示以(i, j)为右下顶点的最大全1矩阵的边长.

状态转移方程:

if matrix[i][j] == 0
	dp[i][j] = 0
else                 // 此时为dp[i-1][j-1], dp[i-1][j], dp[i][j-1] 确定的区域的最大全1矩阵
	dp[i][j] = min{dp[i-1][j-1], dp[i-1][j], dp[i][j-1]} + 1	// 得到此方程需要一定推导, 纸笔画一下

边界: if i == 0 or j == 0: dp[i][j] = matrix[i][j]

答案: max{dp[i][j]}^2max{dp[i][j]}2

public class Solution {
    /**
     * @param matrix: a matrix of 0 and 1
     * @return: an integer
     */
    public int maxSquare(int[][] matrix) {
        // write your code here
        int ans = 0;
        int n = matrix.length;
        int m;
        if (n > 0)
            m = matrix[0].length;
        else 
            return ans;
        int [][]res = new int [n][m];
        for (int i = 0; i < n; i++) {
            res[i][0] = matrix[i][0];
            ans = Math.max(res[i][0] , ans);
            for (int j = 1; j < m; j++) {
                if (i > 0) {
                    if (matrix[i][j] > 0) {
                        res[i][j] = Math.min(res[i-1][j], Math.min(res[i][j-1], res[i-1][j-1])) + 1;
                    } else {
                        res[i][j] = 0;
                    }
                    
                } else {
                    res[i][j] = matrix[i][j];
                }
                ans = Math.max(res[i][j], ans);
            }
        }
        return ans * ans;
    }
}

  

以上是关于Maximal Square的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Maximal Square

221. Maximal Square

Maximal Square

Maximal Square

221. Maximal Square

221. Maximal Square