[LeetCode] Number of Ways of Cutting a Pizza

1444. Number of Ways of Cutting a Pizza

Given a rectangular pizza represented as a rows x cols matrix containing the following characters: ‘A’ (an apple) and ‘.’ (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts.

For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.

Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.

  • Time : O(nm + a)
  • Space : O(nmk)
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
class Solution {
//k, r, c
int dp[10][51][51];
int n, m, mod = 1e9+7;
bool valid(vector<string>& pizza, int r, int c) {
for(int i = r; i < n; i++) {
for(int j = c; j < m; j++) {
if(pizza[i][j] == 'A') return true;
}
}
return false;
}
int solution(vector<string>& p, int k, int r, int c) {
if(r == n or c == m) return 0;
if(dp[k][r][c] != -1) return dp[k][r][c];
if(!k) return dp[k][r][c] = valid(p,r,c);

int nr = r, nc = c;
bool brk = false;
for(; nr < n and !brk; nr++) {
for(int i = c; i < m and !brk; i++) {
if(p[nr][i] == 'A') brk = true;
}
}

brk = false;
for(; nc < m and !brk; nc++) {
for(int i = r; i < n and !brk; i++) {
if(p[i][nc] == 'A') brk = true;
}
}

dp[k][r][c] = 0;

for(; nr < n; nr++) {
dp[k][r][c] = (dp[k][r][c] + solution(p,k-1,nr,c)) % mod;
}

for(; nc < m; nc++) {
dp[k][r][c] = (dp[k][r][c] + solution(p,k-1,r,nc)) % mod;
}

return dp[k][r][c];
}
public:
int ways(vector<string>& pizza, int k) {
memset(dp,-1,sizeof(dp));
n = pizza.size(), m = pizza[0].size();
return solution(pizza, k-1, 0,0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/16/PS/LeetCode/number-of-ways-of-cutting-a-pizza/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.