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.

你可能感兴趣的:(Leetcode: Smallest Rectangle Enclosing Black Pixels)