*LeetCode-Smallest Rectangle Enclosing Black Pixels

22 篇文章 0 订阅
8 篇文章 0 订阅

常规做法dfs bfs O(mn)

bfs需要新建一个class存坐标 dfs不用存 更简便一点 记得每次访问过1后要给他设置成0

public class Solution {
    int minX = Integer.MAX_VALUE, maxX = 0, minY = Integer.MAX_VALUE, maxY = 0;
    public int minArea(char[][] image, int x, int y) {
        if ( image == null || image.length == 0 || image[ 0 ].length == 0 )
            return 0;
        dfs ( image, x, y );
        return ( maxX - minX + 1 ) * ( maxY - minY + 1 );
    }
    public void dfs ( char[][] image, int x, int y ){
        int m = image.length;
        int n = image[ 0 ].length;
        if ( x < 0 || x >= m || y < 0 || y >= n || image [x][y] == '0' )
            return;
        image[x][y] = '0';
        minX = Math.min( minX, x );
        maxX = Math.max( maxX, x );
        minY = Math.min( minY, y );
        maxY = Math.max( maxY, y );
        dfs ( image, x - 1, y );
        dfs ( image, x + 1, y );
        dfs ( image, x, y - 1 );
        dfs ( image, x, y + 1 );
    }
}


还有更快的就是binary search 做四次 寻找边界

[0,y)  找left 找的是最左边的1

[y + 1, n) 找right 找的是右边第一个0

top bottom同理

那个boolean只是为了区分这次是往哪边找 不同方向start和end移动方式不一样

最后算面积的时候right - left不用再加1了

public class Solution {
    public int minArea(char[][] image, int x, int y) {
        int m = image.length;
        int n = image[ 0 ].length;
        int left = searchCol ( image, 0, y, true );
        int right = searchCol ( image, y + 1, n, false );
        int top = searchRow ( image, 0, x, true );
        int bottom = searchRow ( image, x + 1, m, false );
        return  ( right - left ) * ( bottom - top );
    }
    public int searchCol ( char[][]image, int start, int end, boolean left ){
        int row = image.length;
        while ( start < end ){
            int mid = start + ( end - start ) / 2;
            int k = 0;
            while ( k < row && image[ k ][ mid ] == '0')
                k ++;
            if ( k < row == left )
                end = mid;
            else 
                start = mid + 1;
        }
        return start;
    }
    public int searchRow ( char[][] image, int start, int end, boolean top ){
        int col = image[ 0 ].length;
        while ( start < end ){
            int mid = start + ( end - start )/ 2;
            int k = 0;
            while ( k < col && image [ mid ][ k ] == '0' )
                k ++;
            if ( k < col == top )
                end = mid;
            else
                start = mid + 1;
        }
        return start;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值