leetcode 85. 가장 큰 직사각형

leetcode 85. 가장 큰 직사각형

질문 스템

0과 1 만 포함하고 행 x 열의 크기가 포함 된 2 차원 이진 행렬이 주어지면 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 :
입력 : 행렬 = []
출력 : 0

예 3 :
입력 : 행렬 = [[ "0"]]
출력 : 0

예 4 :
입력 : 행렬 = [[ "1"]]
출력 : 1

예 5 :
입력 : matrix = [[ "0", "0"]]
출력 : 0

팁 :
행 == 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