leetcode 85.最大矩形

leetcode 85.最大矩形

题干

给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例 1:
输入:matrix = [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“1”],[“1”,“0”,“0”,“1”,“0”]]
输出:6
解释:最大矩形如上图所示。

示例 2:
输入:matrix = []
输出:0

示例 3:
输入:matrix = [[“0”]]
输出:0

示例 4:
输入:matrix = [[“1”]]
输出:1

示例 5:
输入:matrix = [[“0”,“0”]]
输出:0

提示:
rows == matrix.length
cols == matrix[0].length
0 <= row, cols <= 200
matrix[i][j] 为 ‘0’ 或 ‘1’

题解

遍历矩阵,记录每个1右侧连续1的个数(包括自己),然后将1的坐标存入队列,
然后遍历队列中每个1的坐标,检查以这个1为左上角时所能形成的面积最大的矩形,
策略为检查下方行的1的个数,不断取 已遍历的行数 * 已出现单行1出现的最少次数 的最大值为面积

class Solution {
    
    
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
    
    
        int rows = matrix.size();
        if(rows == 0){
    
    
            return 0;
        }
        int cols = matrix[0].size();
        int maxRectangleArea = 0;
        vector<vector<int> > rightContinuousOneCount(rows,vector<int>(cols,0));
        queue<pair<int,int> > onePosition;
        for(int i = 0 ; i < rows ; ++i){
    
    
            for(int j = 0 ; j < cols ; ++j){
    
    
                if(matrix[i][j] == '1'){
    
    
                    onePosition.push({
    
    i,j});
                    int tempCols = j + 1;
                    int tempRightContinuousOneCount = 1;
                    while(tempCols < cols && matrix[i][tempCols] == '1'){
    
    
                        tempRightContinuousOneCount++;
                        tempCols++;
                    }
                    rightContinuousOneCount[i][j] = tempRightContinuousOneCount;
                }
            }
        }
        while(!onePosition.empty()){
    
    
            int currentRow = onePosition.front().first;
            int currentCol = onePosition.front().second;
            onePosition.pop();
            int tempMaxArea = rightContinuousOneCount[currentRow][currentCol];
            int minRowLength = tempMaxArea;
            int rowsCount = 1;
            currentRow++;
            rowsCount++;
            while(currentRow < rows && rightContinuousOneCount[currentRow][currentCol] > 0){
    
    
                minRowLength = min(minRowLength,rightContinuousOneCount[currentRow][currentCol]);
                tempMaxArea = max(tempMaxArea,rowsCount * minRowLength);

                currentRow++;
                rowsCount++;
            }
            maxRectangleArea = max(maxRectangleArea,tempMaxArea);
            
        }
        return maxRectangleArea;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43662405/article/details/111766494