Skip to content

Commit 2f5a10b

Browse files
committed
Update smallest-rectangle-enclosing-black-pixels.cpp
1 parent 2f3285a commit 2f5a10b

File tree

1 file changed

+43
-2
lines changed

1 file changed

+43
-2
lines changed

C++/smallest-rectangle-enclosing-black-pixels.cpp

+43-2
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,52 @@
11
// Time: O(nlogn)
22
// Space: O(1)
33

4+
// Using template.
45
class Solution {
56
public:
67
int minArea(vector<vector<char>>& image, int x, int y) {
78
using namespace std::placeholders; // for _1, _2, _3...
89

10+
const auto searchColumns =
11+
[](const vector<vector<char>>& image, bool has_one, const int mid) {
12+
return has_one == any_of(image.cbegin(), image.cend(),
13+
[=](const vector<char>& row) { return row[mid] == '1'; });
14+
};
15+
const auto searchRows =
16+
[](const vector<vector<char>>& image, bool has_one, const int mid) {
17+
return has_one == any_of(image[mid].cbegin(), image[mid].cend(),
18+
[](const char& col) { return col == '1'; });
19+
};
20+
21+
const int left = binarySearch(0, y - 1, bind(searchColumns, image, true, _1));
22+
const int right = binarySearch(y + 1, image[0].size() - 1, bind(searchColumns, image, false, _1));
23+
const int top = binarySearch(0, x - 1, bind(searchRows, image, true, _1));
24+
const int bottom = binarySearch(x + 1, image.size() - 1, bind(searchRows, image, false, _1));
25+
26+
return (right - left) * (bottom - top);
27+
}
28+
29+
private:
30+
template<typename T>
31+
int binarySearch(int left, int right, const T& find) {
32+
while (left <= right) {
33+
const int mid = left + (right - left) / 2;
34+
if (find(mid)) {
35+
right = mid - 1;
36+
} else {
37+
left = mid + 1;
38+
}
39+
}
40+
return left;
41+
}
42+
};
43+
44+
// Using std::bind().
45+
class Solution2 {
46+
public:
47+
int minArea(vector<vector<char>>& image, int x, int y) {
48+
using namespace std::placeholders; // for _1, _2, _3...
49+
950
const auto searchColumns =
1051
[](const vector<vector<char>>& image, bool has_one, const int mid) {
1152
return has_one == any_of(image.cbegin(), image.cend(),
@@ -46,8 +87,8 @@ class Solution {
4687
}
4788
};
4889

49-
50-
class Solution2 {
90+
// Using lambda.
91+
class Solution3 {
5192
public:
5293
int minArea(vector<vector<char>>& image, int x, int y) {
5394
const auto searchColumns =

0 commit comments

Comments
 (0)