leetcode 301: Smallest Rectangle Enclosing Black Pixels

Smallest Rectangle Enclosing Black Pixels

Total Accepted: 575 Total Submissions: 1481 Difficulty: Medium

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.

[CODE]

public class Solution {
    int l,r,u,d;
    
    public int minArea(char[][] image, int x, int y) {
        //input check
        u=x;
        d=x;
        l=y;
        r=y;
        int m = image.length-1;
        int n = image[0].length-1;
        
        boolean[][] visited = new boolean[m+1][n+1];
        
        search(image, visited, x, y, m, n);
        
        return (r-l+1) * (d-u+1);
    }
    
    private void search(char[][] image, boolean[][] visited, int x, int y, int m, int n) {
        if(x<0 || x>m || y<0 || y>n || image[x][y]!='1' || visited[x][y]) return;
        visited[x][y] = true;
        
        if(x<u) u=x;
        else if(x>d)d=x;
        if(y<l) l=y;
        else if(y>r) r=y;
        
        search(image, visited, x-1, y, m, n);
        search(image, visited, x, y-1, m, n);
        search(image, visited, x+1, y, m, n);
        search(image, visited, x, y+1, m, n);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值