LeetCode OJ-- Maximal Rectangle ***@

https://oj.leetcode.com/problems/maximal-rectangle/

给一个二维矩阵,里面只有0 1,求一个最大的矩阵,里面的所有元素都是1.

首先预处理: 0 1 1 1 0 1 1 

做一个二维数组,记录到目前为止本行上连续1的个数,为 0 1 2 3 0 1 2

之后再对每一个位置进行遍历,从行方向向列延伸,记录这个过程中的最大面积。

class Solution {
public:
    int maximalRectangle(vector<vector<char> > &matrix) {
        if(matrix.empty() || matrix.size() == 0 || matrix[0].size() == 0)
            return 0;
        int rows = matrix.size();
        int cols = matrix[0].size();

        vector<vector<int> > row_ones;
        row_ones.resize(rows);
        for(int i = 0; i<rows; i++)
            row_ones[i].resize(cols);
        for(int y = 0; y<rows;y++)
        {
            int count = 0;
            for(int x = cols - 1; x>=0; x--)
            {
                if(matrix[y][x] == '1')
                    count++;
                else
                    count = 0;
                row_ones[y][x] = count;
            }
        }
        int i_max = 0;
        for(int y = 0; y < rows; y++)
        {
            for(int x = 0; x < cols; x++)
            {
                if(row_ones[y][x] > 0)
                {
                    for(int x_length = 1; x_length <= row_ones[y][x]; x_length++)
                    {
                        int y_length = 1;
                        while(y + y_length < rows && row_ones[y+y_length][x] >= x_length)
                            y_length++;
                        int m2 = y_length * x_length;
                        i_max = max(m2,i_max); 
                    }
                }
            }
        }
        return i_max;
    }
};
原文地址:https://www.cnblogs.com/qingcheng/p/3874838.html