zoukankan      html  css  js  c++  java
  • LC 302. Smallest Rectangle Enclosing Black Pixels【lock, hard】

    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.

    Example:

    Input:
    [
      "0010",
      "0110",
      "0100"
    ]
    and x = 0, y = 2
    
    Output: 6


    简单题,记录DFS到达的最大上下左右值。

    class Solution {
    private:
      int arr[4][2];
    public:
      int minArea(vector<vector<char>>& image, int x, int y) {
        arr[0][0] = 1;
        arr[0][1] = 0;
        arr[1][0] = -1;
        arr[1][1] = 0;
        arr[2][0] = 0;
        arr[2][1] = 1;
        arr[3][0] = 0;
        arr[3][1] = -1;
        vector<int> ret;
        //ret.push_back();
        ret.push_back(INT_MAX);
        ret.push_back(INT_MIN);
        ret.push_back(INT_MAX);
        ret.push_back(INT_MIN);
        helper(image, x, y, ret);
        //cout << ret[0] << ret[1] << ret[2] << ret[3] << endl;
        return (ret[1] - ret[0] + 1) * (ret[3] - ret[2] + 1);
      }
      void helper(vector<vector<char>>& image, int x, int y, vector<int>& ret){
        if(image[x][y] == '0') return;
        image[x][y] = '0';
        //if(y == 0) cout << x << endl;
        ret[0] = min(x, ret[0]);
        ret[1] = max(x, ret[1]);
        ret[2] = min(y, ret[2]);
        ret[3] = max(y, ret[3]);
        for(int i=0; i<4; i++){
          if(x + arr[i][0] < image.size() && x + arr[i][0] >= 0 && y + arr[i][1] < image[0].size() && y + arr[i][1] >= 0){
            helper(image, x+arr[i][0], y+arr[i][1], ret);
          }
        }
      }
    };



  • 相关阅读:
    BZOJ3674:可持久化并查集加强版
    BZOJ3772:精神污染
    BZOJ3932:[CQOI2015]任务查询系统
    BZOJ3123:[SDOI2013]森林
    BZOJ1926:[SDOI2010]粟粟的书架
    029 列表类型内置方法
    02 Python爬虫之盗亦有道
    01 Python爬虫之Requests库入门
    028 字符串类型内置方法
    027 数字类型内置方法
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10158694.html
Copyright © 2011-2022 走看看