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);
          }
        }
      }
    };



  • 相关阅读:
    P1772 [ZJOI2006]物流运输
    P4290 [HAOI2008]玩具取名
    P1859 不听话的机器人
    P1841 [JSOI2007]重要的城市
    P2182 翻硬币
    P1908 逆序对(归并排序)
    P1010 幂次方(分治)
    P3386 【模板】二分图匹配
    P2158 [SDOI2008]仪仗队
    P1582 倒水(贪心 + lowbit)
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10158694.html
Copyright © 2011-2022 走看看