每天两道LeetCodeHard:(44)

496 阅读1分钟

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.

解释:

这个题给我们一个矩阵,让我们返回包含所有黑色像素的最小矩阵。给了一个点作为黑色像素的中心点。

思考:

实际上就是让我们找边界,那么找边界肯定是用2分了,但是这个题用的十分巧妙,所以借鉴一下。

答案:

class Solution(object):
    def minArea(self, image, x, y):
        """
        :type image: List[List[str]]
        :type x: int
        :type y: int
        :rtype: int
        """
        m,n = len(image),len(image[0])
        up = binary_search(image, true, 0, x, 0, n, true)
        down = binary_search(image, true, x + 1, m, 0, n, false)
        left = binary_search(image, false, 0, y, up, down, true)
        right = binary_search(image, false, y + 1, n, up, down, false)
        return (right-left)*(down-up)
        def binary_search(image,h,i,j,low,high,opt):
            while i<j :
                k = low
                mid =(i+j)//2
                while k < high and (image[mid][k] if h else image[k][mid])=='0':
                    k+=1
                if k < high == opt:
                    j =mid
                else:
                    i =mid+1
            return i

答案补充:

巧妙就在于使用一个h来代替了4个方向上的遍历,只用写一遍,非常简洁。