|
| 1 | +# Number of Ways of Cutting a Pizza |
| 2 | + |
| 3 | +Problem can be found in [here](https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/)! |
| 4 | + |
| 5 | +### [Solution](/Backtracking/1444-NumberofWaysofCuttingaPizza/solution.py): Backtracking + Prefix Sum + Dyanmic Programming |
| 6 | + |
| 7 | +```python |
| 8 | +def ways(pizza: List[str], k: int) -> int: |
| 9 | + row_num, col_num = len(pizza), len(pizza[0]) |
| 10 | + remaining_graph = [[0] * (col_num+1) for _ in range(row_num+1)] |
| 11 | + for row in range(row_num-1, -1, -1): |
| 12 | + for col in range(col_num-1, -1, -1): |
| 13 | + remaining_graph[row][col] = remaining_graph[row+1][col] + \ |
| 14 | + remaining_graph[row][col+1] - remaining_graph[row+1][col+1] + (pizza[row][col] == "A") |
| 15 | + |
| 16 | + @cache |
| 17 | + def backtracking(row: int, col: int, cut_remained: int) -> int: |
| 18 | + if remaining_graph[row][col] == 0: |
| 19 | + return 0 |
| 20 | + if cut_remained == 0: |
| 21 | + return 1 |
| 22 | + |
| 23 | + answer = 0 |
| 24 | + for new_row in range(row+1, row_num): |
| 25 | + if remaining_graph[row][col] - remaining_graph[new_row][col] > 0: |
| 26 | + answer += backtracking(new_row, col, cut_remained-1) |
| 27 | + |
| 28 | + for new_col in range(col+1, col_num): |
| 29 | + if remaining_graph[row][col] - remaining_graph[row][new_col] > 0: |
| 30 | + answer += backtracking(row, new_col, cut_remained-1) |
| 31 | + |
| 32 | + return answer |
| 33 | + |
| 34 | + return backtracking(0, 0, k-1) % (pow(10, 9)+7) |
| 35 | +``` |
| 36 | + |
| 37 | +Time Complexity: )>), Space Complexity: >), where m and n is the length of row and column, respecitvely. |
0 commit comments