leetcode || 85、Maximal Rectangle

problem:

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

Hide Tags
  Array Hash Table Stack Dynamic Programming
题意:在一个由0、1组成的矩阵中寻找全是1的最大矩形,返回其面积

thinking:

这一题是上一条的变形,具体参考

http://blog.csdn.net/doc_sgl/article/details/11832965

code:

class Solution {
public:
    int largestRectangleArea(int* height, int length) {
        stack<int> stk;
        int i = 0;
        int maxArea = 0;
        while(i < length){
            if(stk.empty() || height[stk.top()] <= height[i]){
                stk.push(i++);
            }else {
                int t = stk.top();
    			stk.pop();
				int area = height[t] * (stk.empty() ? i : i - stk.top() - 1);
                maxArea = maxArea > area ? maxArea : area;
            }
        }
        return maxArea;
    }

int maximalRectangle(vector<vector<char> > &matrix) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int m = matrix.size();
        if(m == 0)return 0;
		int n = matrix[0].size();
        if(n == 0)return 0;

		int** dp = new int*[m];
		for(int i = 0; i < m; ++i){
			dp[i] = new int[n+1];
			memset(dp[i], 0, sizeof(int)*(n+1));
		}
		

		for(int j = 0; j < n; ++j)
			if(matrix[0][j] == '1')dp[0][j] = 1;

		for(int j = 0; j < n; ++j)
			for(int i = 1; i < m; ++i)
				if(matrix[i][j] == '1') dp[i][j] = dp[i-1][j] + 1;

		int maxarea = 0;
		for(int i = 0; i < m; ++i){
			int tmp = largestRectangleArea(dp[i],n+1);
			if(tmp > maxarea)
				maxarea = tmp;
		}

		for(int i = 0; i < m; ++i)
			delete[] dp[i];
		delete[] dp;

		return maxarea;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值