302. Smallest Rectangle Enclosing Black Pixels
Posted jxr041100
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了302. 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.
public class Solution { public int minArea(char[][] image, int x, int y) { if(image == null || image.length == 0) { return 0; } int rowNum = image.length, colNum = image[0].length; int left = binarySearch(image, 0, y, 0, rowNum, true, true); int right = binarySearch(image, y + 1, colNum, 0, rowNum, true, false); int top = binarySearch(image, 0, x, left, right, false, true); int bot = binarySearch(image, x + 1, rowNum, left, right, false, false); return (right - left) * (bot - top); } private int binarySearch(char[][] image, int lo, int hi, int min, int max, boolean searchHorizontal, boolean searchLo) { while(lo < hi) { int mid = lo + (hi - lo) / 2; boolean hasBlackPixel = false; for(int i = min; i < max; i++) { if((searchHorizontal ? image[i][mid] : image[mid][i]) == ‘1‘) { hasBlackPixel = true; break; } } if(hasBlackPixel == searchLo) { hi = mid; } else { lo = mid + 1; } } return lo; } }
以上是关于302. Smallest Rectangle Enclosing Black Pixels的主要内容,如果未能解决你的问题,请参考以下文章
LC 302. Smallest Rectangle Enclosing Black Pixelslock, hard
302. Smallest Rectangle Enclosing Black Pixels
LeetCode 302. Smallest Rectangle Enclosing Black Pixels
Smallest Rectangle Enclosing Black Pixels