[leetcode] 302. Smallest Rectangle Enclosing Black Pixels 解题报告

本文介绍了一种使用深度优先搜索(DFS)算法寻找二进制矩阵中所有黑色像素点所包围最小矩形的方法。通过从指定的黑色像素点出发,递归地探索上下左右相邻的黑色像素点,确定整个黑色区域的边界,进而计算出该矩形的面积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/

An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. The black pixels are connected, i.e., there is only one black region. Pixels are connected horizontally and vertically. Given the location (x, y) of one of the black pixels, return the area of the smallest (axis-aligned) rectangle that encloses all black pixels.

For example, given the following image:

[
  "0010",
  "0110",
  "0100"
]
and x = 0y = 2,

Return 6.


思路: 一个DFS, 搜索最大的'1'的边界. 为了防止访问已经访问过的点, 可以将访问过的'1'都置为'0'. 当然如果不允许改变数组的话还可以用hash来存储已经访问过的点.

现在做这种DFS的题目真的是可以干净利落的秒杀了,几分钟就可以搞定.

代码如下:

class Solution {
public:
    void DFS(vector<vector<char>>& image, int x, int y)
    {
        int m = image.size(), n = image[0].size();
        if(x<0 || x>=m || y<0 || y>=n || image[x][y]=='0') return;
        left = min(left, y);
        right = max(right, y);
        top = min(top, x);
        bot = max(bot, x);
        image[x][y] = '0';
        DFS(image, x+1, y);
        DFS(image, x-1, y);
        DFS(image, x, y+1);
        DFS(image, x, y-1);
    }
    int minArea(vector<vector<char>>& image, int x, int y) {
        if(image.size() ==0) return 0;
        DFS(image, x, y);
        return (right-left+1)*(bot-top+1);
    }
private:
    int left = INT_MAX, right=INT_MIN, top=INT_MAX, bot = INT_MIN;
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值