leetcode85。最大の長方形

leetcode85。最大の長方形

質問の語幹

0と1のみを含む2次元のバイナリ行列と、行のサイズx列が与えられた場合、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