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

leetcode || 85、Maximal Rectangle

时间:2015-04-14 16:40:04      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:leetcode   矩阵   算法   stack   

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;
    }
};


leetcode || 85、Maximal Rectangle

标签:leetcode   矩阵   算法   stack   

原文地址:http://blog.csdn.net/hustyangju/article/details/45043309

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