Skip to content

Commit 35b6e6a

Browse files
Create solution for Leetcode 0302
1 parent 190596e commit 35b6e6a

File tree

1 file changed

+178
-0
lines changed

1 file changed

+178
-0
lines changed
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
---
2+
id: smallest-rectangle-enclosing-black-pixels
3+
title: Smallest Rectangle Enclosing Black Pixels
4+
sidebar_label: 0302-Smallest-Rectangle-Enclosing-Black-Pixels
5+
tags: [Binary Search, Matrix, Array, Hard]
6+
description: Given an image represented by a binary matrix where 0 is a white pixel and 1 is a black pixel, return the area of the smallest rectangle that encloses all black pixels. The black pixels are connected, and the rectangle must be axis-aligned.
7+
8+
---
9+
10+
## Problem Statement
11+
12+
You are given an `m x n` binary matrix `image` where `0` represents a white pixel and `1` represents a black pixel. The black pixels are connected, i.e., there is only one black region. Pixels are connected horizontally and vertically.
13+
14+
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.
15+
16+
**You must write an algorithm with less than O(mn) runtime complexity.**
17+
18+
### Examples
19+
20+
**Example 1:**
21+
22+
```plaintext
23+
Input: image = [["0","0","1","0"],["0","1","1","0"],["0","1","0","0"]], x = 0, y = 2
24+
Output: 6
25+
```
26+
27+
**Example 2:**
28+
29+
```plaintext
30+
Input: image = [["1"]], x = 0, y = 0
31+
Output: 1
32+
```
33+
### Constraints
34+
- m == image.length
35+
- n == image[i].length
36+
- 1 <= m, n <= 100
37+
- image[i][j] is either '0' or '1'.
38+
- 0 <= x < m
39+
- 0 <= y < n
40+
- image[x][y] == '1'
41+
- The black pixels in the image only form one component.
42+
- At most 104 calls will be made to `add` and `find`.
43+
44+
## Solution
45+
46+
### Approach
47+
48+
We use binary search to find the left, right, top, and bottom edges of the rectangle that encloses all the black pixels.
49+
50+
#### Algorithm
51+
52+
`Binary Search` to hold remainder.
53+
54+
- Horizontal Search: Find the top and bottom boundaries of the rectangle by searching for rows that contain black pixels.
55+
- Vertical Search: Find the left and right boundaries of the rectangle by searching for columns that contain black pixels.
56+
57+
#### Implementation
58+
59+
## (Java)
60+
61+
```Java
62+
public class Smallest_Rectangle_Enclosing_Black_Pixels {
63+
64+
public class Solution_BinarySearch {
65+
public int minArea(char[][] image, int x, int y) {
66+
if (image == null || image.length == 0) {
67+
return 0;
68+
}
69+
70+
int m = image.length;
71+
int n = image[0].length;
72+
73+
int up = binarySearch(image, true, 0, x, 0, n, true);
74+
int down = binarySearch(image, true, x + 1, m, 0, n, false);
75+
int left = binarySearch(image, false, 0, y, up, down, true);
76+
int right = binarySearch(image, false, y + 1, n, up, down, false);
77+
78+
return (right - left) * (down - up);
79+
}
80+
81+
int binarySearch(char[][] image, boolean isHorizontal, int i, int j, int low, int high, boolean opt) {
82+
while (i < j) {
83+
int k = low;
84+
int mid = (i + j) / 2;
85+
86+
while (k < high && (isHorizontal ? image[mid][k] : image[k][mid]) == '0') {
87+
++k;
88+
}
89+
90+
if (k < high == opt) {
91+
j = mid;
92+
} else {
93+
i = mid + 1;
94+
}
95+
}
96+
97+
return i;
98+
}
99+
}
100+
101+
class Solution_BruteForce {
102+
public int minArea(char[][] image, int x, int y) {
103+
int rows = image.length, columns = image[0].length;
104+
int top = x, bottom = x, left = y, right = y;
105+
int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
106+
image[x][y] = '2';
107+
Queue<int[]> queue = new LinkedList<>();
108+
queue.offer(new int[]{x, y});
109+
while (!queue.isEmpty()) {
110+
int[] cell = queue.poll();
111+
int row = cell[0], column = cell[1];
112+
for (int[] direction : directions) {
113+
int newRow = row + direction[0], newColumn = column + direction[1];
114+
if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && image[newRow][newColumn] == '1') {
115+
image[newRow][newColumn] = '2';
116+
top = Math.min(top, newRow);
117+
bottom = Math.max(bottom, newRow);
118+
left = Math.min(left, newColumn);
119+
right = Math.max(right, newColumn);
120+
queue.offer(new int[]{newRow, newColumn});
121+
}
122+
}
123+
}
124+
return (bottom - top + 1) * (right - left + 1);
125+
}
126+
}
127+
}
128+
129+
```
130+
131+
## (C++)
132+
``` C++
133+
C++
134+
class TwoSum {
135+
Map<Integer,Boolean> map;
136+
List<Integer> list;
137+
int low = Integer.MAX_VALUE;
138+
int high = Integer.MIN_VALUE;
139+
/** Initialize your data structure here. */
140+
public TwoSum() {
141+
map = new HashMap<>();
142+
list = new LinkedList<>();
143+
}
144+
145+
/** Add the number to an internal data structure..*/
146+
public void add(int number) {
147+
if(map.containsKey(number)){
148+
map.put(number,true);
149+
}else{
150+
map.put(number,false);
151+
list.add(number);
152+
low = Math.min(low,number);
153+
high = Math.max(high,number);
154+
}
155+
}
156+
157+
/** Find if there exists any pair of numbers which sum is equal
158+
* to the value. */
159+
public boolean find(int value) {
160+
if(value < 2* low || value > 2*high) return false;
161+
for(int num : list){
162+
int target = value - num;
163+
if(map.containsKey(target)){
164+
if(num != target) return true;
165+
else if(map.get(target)) return true;
166+
}
167+
}
168+
return false;
169+
}
170+
}
171+
172+
```
173+
174+
### Complexity Analysis
175+
176+
- **Time Complexity**: $O(\log m \cdot n + \log n \cdot m)$, where $m$ is the number of rows and $n$ is the number of columns.
177+
178+
- **Space complexity**: $O(1)$, as we are using a constant amount of extra space for variables and no additional data structures.

0 commit comments

Comments
 (0)