|
| 1 | +/** |
| 2 | + * 1444. Number of Ways of Cutting a Pizza |
| 3 | + * https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given a rectangular pizza represented as a rows x cols matrix containing the following |
| 7 | + * characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut |
| 8 | + * the pizza into k pieces using k-1 cuts. |
| 9 | + * |
| 10 | + * For each cut you choose the direction: vertical or horizontal, then you choose a cut |
| 11 | + * position at the cell boundary and cut the pizza into two pieces. If you cut the pizza |
| 12 | + * vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, |
| 13 | + * give the upper part of the pizza to a person. Give the last piece of pizza to the last person. |
| 14 | + * |
| 15 | + * Return the number of ways of cutting the pizza such that each piece contains at least one apple. |
| 16 | + * Since the answer can be a huge number, return this modulo 10^9 + 7. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {string[]} pizza |
| 21 | + * @param {number} k |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var ways = function(pizza, k) { |
| 25 | + const MOD = 1e9 + 7; |
| 26 | + const rows = pizza.length; |
| 27 | + const cols = pizza[0].length; |
| 28 | + const appleCount = new Array(rows + 1).fill().map(() => new Array(cols + 1).fill(0)); |
| 29 | + const dpCache = new Array(rows + 1).fill().map(() => |
| 30 | + new Array(cols + 1).fill().map(() => new Array(k + 1).fill(-1)) |
| 31 | + ); |
| 32 | + |
| 33 | + for (let i = rows - 1; i >= 0; i--) { |
| 34 | + for (let j = cols - 1; j >= 0; j--) { |
| 35 | + appleCount[i][j] = (pizza[i][j] === 'A' ? 1 : 0) |
| 36 | + + appleCount[i + 1][j] + appleCount[i][j + 1] - appleCount[i + 1][j + 1]; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return countWays(0, 0, k - 1); |
| 41 | + |
| 42 | + function countWays(row, col, cutsLeft) { |
| 43 | + if (appleCount[row][col] === 0) return 0; |
| 44 | + if (cutsLeft === 0) return 1; |
| 45 | + if (dpCache[row][col][cutsLeft] !== -1) return dpCache[row][col][cutsLeft]; |
| 46 | + |
| 47 | + let result = 0; |
| 48 | + |
| 49 | + for (let i = row + 1; i < rows; i++) { |
| 50 | + if (appleCount[row][col] - appleCount[i][col] > 0) { |
| 51 | + result = (result + countWays(i, col, cutsLeft - 1)) % MOD; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + for (let j = col + 1; j < cols; j++) { |
| 56 | + if (appleCount[row][col] - appleCount[row][j] > 0) { |
| 57 | + result = (result + countWays(row, j, cutsLeft - 1)) % MOD; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + dpCache[row][col][cutsLeft] = result; |
| 62 | + return result; |
| 63 | + } |
| 64 | +}; |
0 commit comments