码迷,mamicode.com
首页 > 其他好文 > 详细

Maximal Square

时间:2019-12-21 22:34:38      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:min   code   find   down   htm   eset   sub   ret   规划   

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

标签:min   code   find   down   htm   eset   sub   ret   规划   

原文地址:https://www.cnblogs.com/FLAGyuri/p/12078212.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!