leetcode 3195.包含所有1的最小矩形面积I

发布于:2024-12-19 ⋅ 阅读:(14) ⋅ 点赞:(0)

1.题目要求:
在这里插入图片描述
在这里插入图片描述
2.解题步骤:

class Solution {
public:
    int minimumArea(vector<vector<int>>& grid) {
        //设置二维数组
        deque<deque<int>> row_distance;
        for(int i = 0;i < grid.size();i++){
            //遍历数组,把每行头部1的小标和尾部1的下标代入其中
            deque<int> array;
            array.clear();
            int left = 0;
            int right = grid[i].size() - 1;
            while(left < grid[i].size()&&grid[i][left] != 1){
                left++;
            }
            if(left < grid[i].size()){
                array.push_back(left);
            }
            while(right >= 0&&grid[i][right] != 1){
                right--;
            }
            //如果没有下标,则此行的长度为0
            if(right >= 0){
                array.push_back(right);
            }
            row_distance.push_back(array);
        }
        //把二维数组的头部长度为0的去掉
        while(row_distance[0].size() == 0){
            row_distance.pop_front();
        }
        //把二维数组的尾部长度为0的去掉
        while(row_distance[row_distance.size() - 1].size() == 0){
            row_distance.pop_back();
        }
        //每行长度为零,代表此行无1
        //然后再遍历新数组,找到最长宽度,和最小宽度       
            int minwidth = 0;
            int maxwidth = 0;
            int flag = 1;
            for(int i = 0;i < row_distance.size();i++){
                for(int j = 0;j < row_distance[i].size();j++){
                    if(flag == 1){
                        minwidth = row_distance[i][j];
                        maxwidth = row_distance[i][j];
                        flag = 0;
                    }else{
                        if(row_distance[i][j] < minwidth){
                            minwidth = row_distance[i][j];
                        }
                        if(row_distance[i][j] > maxwidth){
                            maxwidth = row_distance[i][j];
                        }
                    }
                }
            }
            //最后返回值
            return row_distance.size() * (maxwidth - minwidth + 1);
    }
};