题目链接: 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 = 0
,
y = 2
,
Return 6
.
思路: 一个DFS, 搜索最大的'1'的边界. 为了防止访问已经访问过的点, 可以将访问过的'1'都置为'0'. 当然如果不允许改变数组的话还可以用hash来存储已经访问过的点.
代码如下:
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(y, left); right = max(y, right); top = min(top, x); bottom = max(bottom, 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; left =INT_MAX, right=INT_MIN, bottom=INT_MIN, top=INT_MAX; DFS(image, x, y); return (right-left+1)*(bottom-top+1); } private: int left, right, bottom, top; };