1 public class Solution {
 2     private char[][] image;
 3     public int minArea(char[][] image, int x, int y) {
 4         if (image.length == 0 || image[0].length == 0) {
 5             return 0;
 6         }
 7         this.image = image;
 8         int n = image.length, m = image[0].length;
 9         int left = searchRow(0, x, 0, m, true);
10         int right = searchRow(x + 1, n, 0, m, false);
11         int top = searchCols(0, y, 0, n, true);
12         int bottom = searchCols(y + 1, m, 0, n, false);
13         return (right - left) * (bottom - top);
14     }
15     
16     private int searchCols(int i, int j, int top, int bottom, boolean bound) {
17         while (i != j) {
18             int k = top;
19             int mid = (i + j) / 2;
20             while (k < bottom && image[k][mid] == '0') {
21                 k++;
22             }
23             if(k < bottom == bound) {
24                 j = mid;
25             } else {
26                 i = mid + 1;
27             }
28         }
29         return i;
30     }   
31     
32     private int searchRow(int i, int j, int left, int right, boolean bound) {
33         while (i != j) {
34             int k = left;
35             int mid = (i + j) / 2;
36             while (k < right && image[mid][k] == '0') {
37                 k++;
38             }
39             if(k < right == bound) {
40                 j = mid;
41             } else {
42                 i = mid + 1;
43             }
44         }
45         return i;
46     }
47 }

Binary search:

1. The bound is defined to search "0" or "1". When search 0 - x, we want to get the most left "1". So k < right mean there is a one, j = mid. But when we do x - n search, we want to get most left "0". So when k < right, we still need to keep searching mid + 1.

 

posted on 2016-07-06 07:13  keepshuatishuati  阅读(148)  评论(0编辑  收藏  举报