Leetcode #1444: Number of Ways of Cutting a Pizza
In this guide, we solve Leetcode #1444 Number of Ways of Cutting a Pizza in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Memoization, Array, Dynamic Programming, Matrix, Prefix Sum
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
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.
Python Solution
class Solution:
def ways(self, pizza: List[str], k: int) -> int:
def dfs(i: int, j: int, k: int) -> int:
if k == 0:
return int(s[m][n] - s[i][n] - s[m][j] + s[i][j] > 0)
ans = 0
for x in range(i + 1, m):
if s[x][n] - s[i][n] - s[x][j] + s[i][j] > 0:
ans += dfs(x, j, k - 1)
for y in range(j + 1, n):
if s[m][y] - s[i][y] - s[m][j] + s[i][j] > 0:
ans += dfs(i, y, k - 1)
return ans % mod
mod = 10**9 + 7
m, n = len(pizza), len(pizza[0])
s = [[0] * (n + 1) for _ in range(m + 1)]
for i, row in enumerate(pizza, 1):
for j, c in enumerate(row, 1):
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + int(c == 'A')
return dfs(0, 0, k - 1)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.