Skip to content

Commit 24a567d

Browse files
committed
Add lambda solve
1 parent 9e158c5 commit 24a567d

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

695/step2_3.cpp

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
Time : O()
3+
Space : O(N * M)
4+
5+
ラムダを用いてstackへの要素追加部分のロジックを修正したものt
6+
*/
7+
class Solution {
8+
public:
9+
int maxAreaOfIsland(vector<vector<int>>& grid) {
10+
const int row_count = grid.size();
11+
const int col_count = grid.front().size();
12+
auto visited = vector<vector<char>>(row_count, vector<char>(col_count, '0'));
13+
int max_island_area = 0;
14+
for (int row = 0; row < row_count; ++row) {
15+
for (int col = 0; col < col_count; ++col) {
16+
if (grid[row][col] == kSea) {
17+
continue;
18+
}
19+
const int area = CountIslandArea(row, col, row_count, col_count, grid, visited);
20+
max_island_area = max(max_island_area, area);
21+
}
22+
}
23+
return max_island_area;
24+
}
25+
26+
private:
27+
static constexpr int kSea = 0;
28+
29+
int CountIslandArea(const int row, const int col,
30+
const int row_count, const int col_count,
31+
const vector<vector<int>>& grid,
32+
vector<vector<char>>&visited) {
33+
stack<pair<int, int>> next_coordinates;
34+
next_coordinates.emplace(row, col);
35+
int area = 0;
36+
37+
auto emplace_if_countable = [&grid, &visited, &next_coordinates, row_count, col_count](
38+
const int row,
39+
const int col) {
40+
if (!(0 <= row && row < row_count && 0 <= col && col < col_count)) {
41+
return;
42+
}
43+
if (grid[row][col] == kSea) {
44+
return;
45+
}
46+
if (visited[row][col] == '1') {
47+
return;
48+
}
49+
next_coordinates.emplace(row, col);
50+
};
51+
52+
while (!next_coordinates.empty()) {
53+
auto [row, col] = next_coordinates.top();
54+
next_coordinates.pop();
55+
if (visited[row][col] == '1') {
56+
continue;
57+
}
58+
visited[row][col] = '1';
59+
++area;
60+
emplace_if_countable(row + 1, col);
61+
emplace_if_countable(row - 1, col);
62+
emplace_if_countable(row, col + 1);
63+
emplace_if_countable(row, col - 1);
64+
}
65+
return area;
66+
}
67+
};

0 commit comments

Comments
 (0)