Program to count how many ways we can cut the matrix into k pieces in python

Suppose we have a binary matrix and a value k. We want to split the matrix into k pieces such that each piece contains at least one 1. The cutting rules are:

  1. Select a direction: vertical or horizontal
  2. Select an index in the matrix to cut into two sections
  3. If we cut vertically, we can no longer cut the left part but can only continue cutting the right part
  4. If we cut horizontally, we can no longer cut the top part and can only continue cutting the bottom part

We need to find the number of different ways to divide the matrix. If the answer is very large, return result mod (10^9 + 7).

Example Matrix

Consider this 3x3 binary matrix with k = 2:

1 1 0
1 0 1
1 1 1

The output will be 4, as we can cut vertically twice and horizontally twice.

Algorithm Steps

  • Create a suffix sum matrix to count 1s in each submatrix
  • Use dynamic programming with memoization
  • For each position, try all valid horizontal and vertical cuts
  • Ensure each piece contains at least one 1
  • Return the total number of ways modulo 10^9 + 7

Implementation

from collections import defaultdict

class Solution:
    def solve(self, matrix, k):
        p = 10 ** 9 + 7
        
        m, n = len(matrix), len(matrix[0])
        counts = defaultdict(int)
        
        # Build suffix sum matrix to count 1s
        for i in range(m)[::-1]:
            for j in range(n)[::-1]:
                counts[(i, j)] = (counts[(i + 1, j)] + 
                                counts[(i, j + 1)] - 
                                counts[(i + 1, j + 1)] + 
                                matrix[i][j])
        
        def f(x, y, c):
            count = counts[(x, y)]
            if c == 0:
                return 1 if count > 0 else 0
            
            ans = 0
            # Try horizontal cuts
            for i in range(x + 1, m):
                if 0 < counts[(i, y)] < count:
                    ans += f(i, y, c - 1)
            
            # Try vertical cuts
            for j in range(y + 1, n):
                if 0 < counts[(x, j)] < count:
                    ans += f(x, j, c - 1)
            
            return ans % p
        
        return f(0, 0, k - 1)

# Test the solution
ob = Solution()
matrix = [
    [1, 1, 0],
    [1, 0, 1],
    [1, 1, 1],
]
k = 2
print(ob.solve(matrix, k))
4

How It Works

The algorithm uses a suffix sum matrix to efficiently count the number of 1s in any submatrix starting from position (i, j). The recursive function f(x, y, c) represents the number of ways to cut the submatrix starting at (x, y) into c pieces.

For each position, we try all possible horizontal cuts (cutting below row i) and vertical cuts (cutting after column j). A cut is valid only if both the cut piece and remaining piece contain at least one 1.

Key Points

  • The suffix sum matrix allows O(1) lookup of 1s count in any submatrix
  • We use dynamic programming with memoization for efficiency
  • Each cut must ensure both pieces contain at least one 1
  • The cutting restrictions prevent us from cutting previously cut sections

Conclusion

This solution uses dynamic programming with suffix sum optimization to count valid matrix cutting ways. The time complexity is O(m²n² × k) where m,n are matrix dimensions and k is the number of pieces.

Updated on: 2026-03-25T13:10:34+05:30

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements