Skip to content

Commit 7c998c5

Browse files
authored
Create 1444. Number of Ways of Cutting a Pizza 31 march
1444. Number of Ways of Cutting a Pizza
1 parent 8632b3e commit 7c998c5

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Solution {
2+
private:
3+
static constexpr int kMod = 1'000'000'007;
4+
vector<vector<vector<int>>> dp;
5+
vector<vector<int>> prefix;
6+
7+
public:
8+
int ways(vector<string>& pizza, int k) {
9+
const int M = pizza.size();
10+
const int N = pizza[0].size();
11+
// dp[m][n][k] := # of ways to cut pizza[m:M][n:N] w/ k cuts
12+
dp.resize(M, vector<vector<int>>(N, vector<int>(k, -1)));
13+
prefix.resize(M + 1, vector<int>(N + 1));
14+
15+
for (int i = 0; i < M; ++i)
16+
for (int j = 0; j < N; ++j)
17+
prefix[i + 1][j + 1] = (pizza[i][j] == 'A') + prefix[i][j + 1] +
18+
prefix[i + 1][j] - prefix[i][j];
19+
20+
return ways(0, 0, k - 1, M, N);
21+
}
22+
23+
int ways(int m, int n, int k, const int M, const int N) {
24+
if (k == 0)
25+
return 1;
26+
if (dp[m][n][k] >= 0)
27+
return dp[m][n][k];
28+
29+
dp[m][n][k] = 0;
30+
31+
for (int i = m + 1; i < M; ++i) // Cut horizontally
32+
if (hasApple(m, i, n, N) && hasApple(i, M, n, N))
33+
dp[m][n][k] = (dp[m][n][k] + ways(i, n, k - 1, M, N)) % kMod;
34+
35+
for (int j = n + 1; j < N; ++j) // Cut vertically
36+
if (hasApple(m, M, n, j) && hasApple(m, M, j, N))
37+
dp[m][n][k] = (dp[m][n][k] + ways(m, j, k - 1, M, N)) % kMod;
38+
39+
return dp[m][n][k];
40+
}
41+
// HasApple of pizza[row1..row2)[col1..col2)
42+
bool hasApple(int row1, int row2, int col1, int col2) {
43+
return (prefix[row2][col2] - prefix[row1][col2] - prefix[row2][col1] +
44+
prefix[row1][col1]) > 0;
45+
};
46+
};

0 commit comments

Comments
 (0)