首页 > 代码库 > 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 = 0y = 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