forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-number-of-fish-in-a-grid.cpp
83 lines (79 loc) · 2.64 KB
/
maximum-number-of-fish-in-a-grid.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Time: O(m * n)
// Space: O(m + n)
// bfs
class Solution {
public:
int findMaxFish(vector<vector<int>>& grid) {
static const vector<pair<int, int>> DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
const auto& bfs = [&](int i, int j) {
int result = grid[i][j];
grid[i][j] = 0;
vector<pair<int ,int>> q = {{i, j}};
while (!empty(q)) {
vector<pair<int, int>> new_q;
for (const auto& [i, j] : q) {
for (const auto& [di, dj] : DIRECTIONS) {
const int ni = i + di, nj = j + dj;
if (!(0 <= ni && ni < size(grid) &&
0 <= nj && nj < size(grid[0]) &&
grid[ni][nj])) {
continue;
}
result += grid[ni][nj];
grid[ni][nj] = 0;
new_q.emplace_back(ni, nj);
}
}
q = move(new_q);
}
return result;
};
int result = 0;
for (int i = 0; i < size(grid); ++i) {
for (int j = 0; j < size(grid[0]); ++j) {
if (grid[i][j]) {
result = max(result, bfs(i, j));
}
}
}
return result;
}
};
// Time: O(m * n)
// Space: O(m * n)
// dfs
class Solution2 {
public:
int findMaxFish(vector<vector<int>>& grid) {
static const vector<pair<int, int>> DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
const auto& dfs = [&](int i, int j) {
int result = grid[i][j];
grid[i][j] = 0;
vector<pair<int ,int>> stk = {{i, j}};
while (!empty(stk)) {
const auto [i, j] = stk.back(); stk.pop_back();
for (const auto& [di, dj] : DIRECTIONS) {
const int ni = i + di, nj = j + dj;
if (!(0 <= ni && ni < size(grid) &&
0 <= nj && nj < size(grid[0]) &&
grid[ni][nj])) {
continue;
}
result += grid[ni][nj];
grid[ni][nj] = 0;
stk.emplace_back(ni, nj);
}
}
return result;
};
int result = 0;
for (int i = 0; i < size(grid); ++i) {
for (int j = 0; j < size(grid[0]); ++j) {
if (grid[i][j]) {
result = max(result, dfs(i, j));
}
}
}
return result;
}
};