Leetcode BinarySearch 302 Smallest Rectangle Enclosing Black Pixels

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.

Example:

Input:
[
“0010”,
“0110”,
“0100”
]
and x = 0, y = 2

Output: 6

solution : binary search

class Solution {
    public int minArea(char[][] image, int x, int y) {
        int m = image.length;
        int n = image[0].length;
        int l = 0;
        int r = 0;
        int t = 0;
        int b = 0;
        
        // vertical (column) 
        // left
        int lo = 0;
        int hi = y;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (emptyColumn(image, mid)) {
                lo = mid+1;
            } else {
                hi = mid;
            }
        }
        l = lo;
        
        lo = y;
        hi = n - 1;
        while (lo < hi) {
            int mid = lo + (hi - lo + 1) / 2;
            if (emptyColumn(image, mid)) {
                hi = mid - 1;
            } else {
                lo = mid;
            }
        }
        r = lo;
        
        
        // horizontal (row)
        lo = 0;
        hi = x;
        while (lo + 1 < hi) {
            int mid = lo + (hi - lo) / 2;
            if (emptyRow(image, mid)) {
                lo = mid;
            } else {
                hi = mid;
            }
        }
        t  = (emptyRow(image, lo)) ? hi:lo;
        
        lo = x;
        hi = m - 1;
        while (lo + 1 < hi) {
            int mid = lo + (hi - lo) / 2;
            if (emptyRow(image, mid)) {
                hi = mid;
            } else {
                lo = mid;
            }
        }
        b = (emptyRow(image, hi)) ? lo:hi;
        
        return (b - t + 1) * (r - l + 1);
    }
    
    public boolean emptyRow(char[][] image, int num) {
        for (char tmp : image[num]) {
            if (tmp == '1') 
                return false;
        }
        
        return true;
    }
    
    public boolean emptyColumn(char[][] image, int num) {
        int m = image.length;
        for (int i = 0; i < m; i++) {
            if (image[i][num] == '1')
                return false;
        }
        
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值