首页 > 代码库 > Smallest Rectangle Enclosing Black Pixels
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,也可以二分查找,因为题目中明确说了,只有一块黑色区域。
代码来自:http://www.cnblogs.com/yrbbest/p/5050022.html
1 public class Solution { 2 public int minArea(char[][] image, int x, int y) { 3 if(image == null || image.length == 0) { 4 return 0; 5 } 6 int rowNum = image.length, colNum = image[0].length; 7 int left = binarySearch(image, 0, y, 0, rowNum, true, true); 8 int right = binarySearch(image, y + 1, colNum, 0, rowNum, true, false); 9 int top = binarySearch(image, 0, x, left, right, false, true);10 int bot = binarySearch(image, x + 1, rowNum, left, right, false, false);11 12 return (right - left) * (bot - top);13 }14 15 private int binarySearch(char[][] image, int lo, int hi, int min, int max, boolean searchHorizontal, boolean searchLo) {16 while(lo < hi) {17 int mid = lo + (hi - lo) / 2;18 boolean hasBlackPixel = false;19 for(int i = min; i < max; i++) {20 if((searchHorizontal ? image[i][mid] : image[mid][i]) == ‘1‘) {21 hasBlackPixel = true;22 break;23 }24 }25 if(hasBlackPixel == searchLo) {26 hi = mid;27 } else {28 lo = mid + 1;29 }30 }31 return lo;32 }33 }
Smallest Rectangle Enclosing Black Pixels
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。