2023-03-31 Daily Challenge

Today I have done leetcode's March LeetCoding Challenge with cpp.

March LeetCoding Challenge 31

Description

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

class Solution {
  int dp[10][50][50];
  int prefixSum[51][51] = {};
  int rows;
  int cols;
  const int MOD = 1e9 + 7;
public:
  int ways(vector<string>& pizza, int k) {
    rows = pizza.size();
    cols = pizza.front().size();
    memset(dp, -1, k * sizeof(dp[0]));
    for(int row = rows - 1; row >= 0; --row) {
      for(int col = cols - 1; col >= 0; --col) {
        prefixSum[row][col] = prefixSum[row][col + 1] + prefixSum[row + 1][col] - prefixSum[row + 1][col + 1] + (pizza[row][col] == 'A');
      }
    }

    return solve(k - 1, 0, 0);
  }

  int solve(int k, int row, int col) {
    if(!prefixSum[row][col]) return 0;
    if(k == 0) return 1;
    if(dp[k][row][col] != -1) return dp[k][row][col];
    int result = 0;
    for(int newRow = row + 1; newRow < rows; ++newRow) {
      if(prefixSum[row][col] - prefixSum[newRow][col] > 0){
        result += solve(k - 1, newRow, col);
        result %= MOD;
      }
    }
    for(int newCol = col + 1; newCol < cols; ++newCol) {
      if(prefixSum[row][col] - prefixSum[row][newCol] > 0) {
        result += solve(k - 1, row, newCol);
        result %= MOD;
      }
    }
    dp[k][row][col] = result;
    return result;
  }
};

// Accepted
// 53/53 cases passed (7 ms)
// Your runtime beats 98.95 % of cpp submissions
// Your memory usage beats 94.5 % of cpp submissions (7.6 MB)