題目:
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
.
鏈接: http://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/
題解:
找到包含所有black pixel的最小矩形。這里我們用二分查找。因為給定black pixel點(x,y),並且所有black pixel都是聯通的,以row search為例, 所有含有black pixel的column,映射到row x上時,必定是連續的。這樣我們可以使用binary search,在0到y里面搜索最左邊含有black pixel的一列。接下來可以繼續搜索上下和右邊界。搜索右邊界和下邊界的時候,其實我們要找的是第一個'0',所以要傳入一個boolean變量searchLo來判斷。
Time Complexity - O(mlogn + nlogm), Space Complexity - O(1)
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; } }
Reference:
https://leetcode.com/discuss/68246/c-java-python-binary-search-solution-with-explanation
https://leetcode.com/discuss/71898/java-concise-binary-search-4x-faster-than-dfs
https://leetcode.com/discuss/68407/clear-binary-search-python
https://leetcode.com/discuss/68233/java-dfs-solution-and-seeking-for-a-binary-search-solution
https://leetcode.com/discuss/68738/very-easy-dfs-java-solution-with-comments
https://leetcode.com/discuss/70670/dfs-bfs-binary-search-and-brute-force-interation