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



猜你喜欢

转载自www.cnblogs.com/ethanhong/p/10158694.html
今日推荐