Smallest Rectangle Enclosing Black Pixels

Another problem where BFS comes handy: https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/

302. 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.
Example:
Input:
[
  "0010",
  "0110",
  "0100"
]
and x = 0, y = 2

Output: 6
Accepted
25,367
Submissions
50,276

Since you're given the coordinates of a black pixel, and the fact that there is only one black region, from the given point perform a BFS keeping track of the leftmost, rightmost, topmost and bottom-most coordinates - these are the boundaries of the rectangle whose area you'll need to return. That's it. Cheers, ACC.


public class Solution
{
    public int MinArea(char[][] image, int x, int y)
    {
        Hashtable visited = new Hashtable();
        Queue<QueueItem> queue = new Queue<QueueItem>();
        int left = y;
        int right = y;
        int top = x;
        int bottom = x;

        QueueItem qi = new QueueItem(x, y);
        queue.Enqueue(qi);
        visited.Add(qi.key, true);

        while (queue.Count > 0)
        {
            QueueItem current = queue.Dequeue();

            if (current.y < left) left = current.y;
            if (current.y > right) right = current.y;
            if (current.x < top) top = current.x;
            if (current.x > bottom) bottom = current.x;

            int[] dx = { 1, -1, 0, 0 };
            int[] dy = { 0, 0, 1, -1 };

            for (int i = 0; i < dx.Length; i++)
            {
                int nx = current.x + dx[i];
                int ny = current.y + dy[i];

                QueueItem nqi = new QueueItem(nx, ny);
                if (nx >= 0 &&
                    nx < image.Length &&
                    ny >= 0 &&
                    ny < image[0].Length &&
                    image[nx][ny] == '1' &&
                    !visited.ContainsKey(nqi.key))
                {
                    visited.Add(nqi.key, true);
                    queue.Enqueue(nqi);
                }
            }
        }

        return (right - left + 1) * (bottom - top + 1);
    }
}

public class QueueItem
{
    public int x;
    public int y;
    public string key;

    public QueueItem(int x, int y)
    {
        this.x = x;
        this.y = y;
        this.key = x.ToString() + "@" + y.ToString();
    }
}

Comments

Post a Comment

Popular posts from this blog

Count Binary Substrings

Count Vowels Permutation: Standard DP

Maximum Number of Balloons