Tuesday, May 3, 2016

LeetCode Q302: Smallest Rectangle Enclosing Black Pixels (hard)

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 = 0y = 2,
Return 6.

Solution:
I can't imagine in the first place how people can think of using Binary Search to solve this problem. So, when you get your brute force answer don't stop there, think deeper.
Suppose we have a 2D array
"000000111000000"
"000000101000000"
"000000101100000"
"000001100100000"
Imagine we project the 2D array to the bottom axis with the rule "if a column has any black pixel it's projection is black otherwise white". The projected 1D array is
This means we can do a binary search in each half to find the boundaries, if we know one black pixel's position. And we do know that.
To find the left boundary, do the binary search in the [0, y) range and find the first column vector who has any black pixel.
To determine if a column vector has a black pixel is O(m) so the search in total is O(m log n)
We can do the same for the other boundaries. The area is then calculated by the boundaries. Thus the algorithm runs in O(m log n + n log m)

No comments:

Post a Comment