LC 302. Smallest Rectangle Enclosing Black Pixelslock, hard

Posted ethanhong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC 302. Smallest Rectangle Enclosing Black Pixelslock, 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);
      }
    }
  }
};

 












以上是关于LC 302. Smallest Rectangle Enclosing Black Pixelslock, hard的主要内容,如果未能解决你的问题,请参考以下文章

302. Smallest Rectangle Enclosing Black Pixels

302. Smallest Rectangle Enclosing Black Pixels

lc 632. Smallest Range

LC 988. Smallest String Starting From Leaf

[LC] 373. Find K Pairs with Smallest Sums

LeetCode 302. Smallest Rectangle Enclosing Black Pixels