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.
Example 1:

Input: pizza = ["A..","AAA","..."], k = 3
Output: 3
Explanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.
Example 2:
Input: pizza = ["A..","AA.","..."], k = 3
Output: 1
Example 3:
Input: pizza = ["A..","A..","..."], k = 1
Output: 1
Constraints:
1 <= rows, cols <= 50
rows == pizza.length
cols == pizza[i].length
1 <= k <= 10
pizza
consists of characters'A'
and'.'
only.
Solution
The First idea is to use a recursive to enumerate all possible combination during the process.
It contains many choices during the process, for example, taken (if we can) or not taken.
Therefore the scope of the problem can reduced with one choice has been made.
Another is the tricky part of this problem is how to identify wheither a cut is allowed. ->presum matrix to record the number apple in a particular area, for example,
presum[i][j] is the number of apple in martix[a][b], far all a in [i, m-1], for all b in [j, n-1]/
So when we want to identify if a cut can be made, just check the presum[startRow][startCol] - presum[cutPointRow][cutPointCol] > 0
int mod = (int) (1e9 + 7);
Integer[][][] dp;
int m = 0;
int n = 0;
public int ways(String[] pizza, int k) {
m = pizza.length;
n = pizza[0].length();
int[][] presum = new int[m+1][n+1];
dp = new Integer[m][n][k];
for(int i = m-1; i >= 0; i--) {
for(int j = n-1; j >= 0; j--) {
presum[i][j] = presum[i+1][j] + presum[i][j+1] - presum[i+1][j+1];
presum[i][j] += (pizza[i].charAt(j) == 'A')? 1 : 0;
}
}
return helper(0, 0, k-1, presum);
}
public int helper(int row, int col, int k, int[][] presum){
if(presum[row][col] == 0) return 0;
if(k == 0) return 1;
if(dp[row][col][k] != null) return dp[row][col][k];
int ans = 0;
for(int i = row+1; i < m; i++) {
if(presum[row][col] - presum[i][col] > 0){
ans = (ans + helper(i, col, k-1, presum)) % mod;
}
}
for(int i = col+1; i < n; i++) {
if(presum[row][col] - presum[row][i] > 0){
ans = (ans + helper(row, i, k-1, presum))% mod;
}
}
return dp[row][col][k] = ans;
}
Last updated
Was this helpful?