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

Maximal Square

时间:2015-06-06 14:44:05      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:

Problem:

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.

Solutions:

定义p[i][j]为右下角是点matrix[i][j]的最大全‘1‘正方形,于是

  若matrix[i][j] == 0,则p[i][j] = 0;

  若i == 0,则p[0][j] = matrix[0][j] == ‘0‘ ? 0 : 1;

  若j == 0,则p[i][0] = matrix[i][0] == ‘0‘ ? 0 : 1;

  若i > 0 && j > 0 && matrix[i][j] == ‘1‘, 则p[i][j] = min(p[i-1][j], p[i][j-1], p[i-1][j-1]) + 1;

分析发现p[i][j]只依赖于上一行p[i-1][]和当前行的前一个元素p[i][j-1],于是空间开销可以进一步压缩到O(列数),以下是实现代码(C++):

int maximalSquare(vector<vector<char>>& matrix) {
        int n, m;
        if((n = matrix.size()) < 1 || (m = matrix[0].size()) < 1) return 0;
        vector<int> dp(m, 0);
        int pre, cur, res = 0;
        for(int i = 0; i < n; ++i){
            pre = matrix[i][0] - 0;
            if(res < pre) res = pre;
            for(int j = 1; j < m; ++j){
                if(matrix[i][j] == 1){
                    cur = min(pre, min(dp[j-1], dp[j])) + 1;
                    if(cur > res) res = cur;
                }else{
                    cur = 0;
                }
                dp[j-1] = pre;
                pre = cur;
            }
            dp[m-1] = pre;
        }
        return res * res;
    }

 

Maximal Square

标签:

原文地址:http://www.cnblogs.com/poweryong/p/4556501.html

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