Leetcode Maximal Rectangle

OpenSoucre發表於2014-06-25

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

時間複雜度O(n^3),最大全1子矩陣,利用直方圖求解,可以參考對最大全零子矩陣的研究

class Solution {
public:
    int maximalRectangle(vector<vector<char> > &matrix) {
        if(matrix.empty()) return 0;
        int w = matrix[0].size(),h = matrix.size(), res = 0;
        for(int i = 0 ; i < w; ++ i){
            char row[h];
            for(int j =  i ; j < w; ++ j){
                if( j == i ){
                    for(int k = 0 ; k <  h; ++ k){
                        row[k] = matrix[k][i];
                    }
                }else{
                    for(int k = 0 ; k < h; ++ k){
                        if(matrix[k][j]!=matrix[k][j-1]) row[k]='X';
                    }
                    
                }
                int cnt = 0 ,maxCnt = 0;
                for(int k = 0 ; k < h ; ++ k){
                    if(row[k] == 'X' || row[k] == '0') cnt = 0;
                    else if((cnt > 0) && row[k]==row[k-1] ){
                        cnt++;
                    }else cnt = 1;
                    maxCnt = max(maxCnt, cnt);
                }
                res = max(res,maxCnt*(j-i+1));
            }
        }
        return res;
    }
};

 

相關文章