Smallest Rectangle Enclosing Black Pixels

update Aug 17,2017 17:20

LeetCodearrow-up-right

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.

Basic Idea:

思路 1:二分法 上下左右分别搜索,时间复杂度应该是 O(mlogn + nlogm).

思路 2:BFS 或者 DFS 时间复杂度为O(Number of black pixels) == O(mn).

Python Code:

二分法:

Java Code:

DFS:

BFS:

update Dec 16, 2017

Python BFS solution