Leetcode: Smallest Rectangle Enclosing Black Pixels

Question

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.

Hide Company Tags Google
Hide Tags Binary Search


My Solution

Accept
Time complexity: O(mn)

class Solution(object):
    def minArea(self, image, x, y):
        """
        :type image: List[List[str]]
        :type x: int
        :type y: int
        :rtype: int
        """

        if len(image)==0 or len(image[0])==0 or x<0 or y<0:
            return 0

        res = [y, y, x, x]
        dict_direct = [ [1,0], [-1,0], [0,1], [0,-1] ]
        m,n = len(image), len(image[0])

        visited = [[0]*n for dummy in range(m)]
        self.helper( image, x, y, visited, res, dict_direct)

        return (res[1]-res[0]+1)*(res[2]-res[3]+1)


    def helper(self, image, cur_i, cur_j, visited, res, dict_direct):
        visited[cur_i][cur_j] = 1
        res[0], res[1], res[2], res[3] = \
                min(res[0], cur_j), max(res[1], cur_j), \
                max(res[2], cur_i), min(res[3], cur_i)

        for ind in range(4):
            next_i = cur_i + dict_direct[ind][0]
            next_j = cur_j + dict_direct[ind][1]

            if next_i<0 or next_i==len(image) \
               or next_j<0 or next_j==len(image[0]) \
               or image[next_i][next_j]=="0" \
               or visited[next_i][next_j]==1:
                   continue

            self.helper(image, next_i, next_j, visited, res, dict_direct)

        return 

Other's Solutionf

Get idea from 1, 2, 3.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值