首页 > 其他 > 详细

【Leetcode】Maximal Square

时间:2016-05-31 06:28:41      阅读:126      评论:0      收藏:0      [点我收藏+]

题目链接:https://leetcode.com/problems/maximal-square/

题目:

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.

思路:

用c[i][j]表示在长为i、宽为j的矩阵里面,包含matrix[i][j]这个点的最大正方形的长。

显然c[i][j]的大小跟c[i-1][j]、c[i][j-1]、c[i-1][j-1]有关。画图观察c[i-1][j]、c[i][j-1]、c[i-1][j-1]包围起来的面积

可知 c[i][j] = min(c[i-1][j]、c[i][j-1]、c[i-1][j-1]) +1

算法

public int maximalSquare(char[][] matrix) {  
        if (matrix.length == 0)  
            return 0;  
        int max = 0;  
        int c[][] = new int[matrix.length][matrix[0].length];  
        for (int i = 0; i < matrix.length; i++) {  
            for (int j = 0; j < matrix[0].length; j++) {  
                if (matrix[i][j] == '0') {  
                    continue;  
                }  
                if (i == 0 || j == 0) {// 在边缘时  
                    c[i][j] = 1;  
                } else {  
                    c[i][j] = Math.min(c[i - 1][j - 1], Math.min(c[i - 1][j], c[i][j - 1])) + 1;  
                }  
                max = Math.max(max, c[i][j]);  
            }  
        }  
        return max * max;  
    }  


【Leetcode】Maximal Square

原文:http://blog.csdn.net/yeqiuzs/article/details/51542403

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!