Number of ways of cutting a Matrix such that atleast one cell is filled in each part | Function to find the number of ways to cut the matrix into the K parts such that each part have atleast one filled cell ; Loop to find prefix sum of the given matrix ; dp ( r , c , 1 ) = 1 if preSum [ r ] else 0 ; Loop to iterate over the dp table of the given matrix ; Check if can cut horizontally at r1 , at least one apple in matrix ( r , c ) -> r1 , C - 1 ; Check if we can cut vertically at c1 , at least one apple in matrix ( r , c ) -> R - 1 , c1 ; Driver Code ; Function Call
def ways ( arr , k ) : NEW_LINE INDENT R = len ( arr ) NEW_LINE C = len ( arr [ 0 ] ) NEW_LINE K = k NEW_LINE preSum = [ [ 0 for _ in range ( C ) ] \ for _ in range ( R ) ] NEW_LINE for r in range ( R - 1 , - 1 , - 1 ) : NEW_LINE INDENT for c in range ( C - 1 , - 1 , - 1 ) : NEW_LINE INDENT preSum [ r ] = arr [ r ] NEW_LINE if r + 1 < R : NEW_LINE INDENT preSum [ r ] += preSum [ r + 1 ] NEW_LINE DEDENT if c + 1 < C : NEW_LINE INDENT preSum [ r ] += preSum [ r ] NEW_LINE DEDENT if r + 1 < R and c + 1 < C : NEW_LINE INDENT preSum [ r ] -= preSum [ r + 1 ] NEW_LINE DEDENT DEDENT DEDENT dp = [ [ [ 0 for _ in range ( C ) ] \ for _ in range ( R ) ] \ for _ in range ( K + 1 ) ] NEW_LINE for k in range ( 1 , K + 1 ) : NEW_LINE INDENT for r in range ( R - 1 , - 1 , - 1 ) : NEW_LINE INDENT for c in range ( C - 1 , - 1 , - 1 ) : NEW_LINE INDENT if k == 1 : NEW_LINE INDENT dp [ k ] [ r ] = 1 if preSum [ r ] > 0 else 0 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ k ] [ r ] = 0 NEW_LINE for r1 in range ( r + 1 , R ) : NEW_LINE INDENT if preSum [ r ] - preSum [ r1 ] > 0 : NEW_LINE INDENT dp [ k ] [ r ] += dp [ k - 1 ] [ r1 ] NEW_LINE DEDENT DEDENT for c1 in range ( c + 1 , C ) : NEW_LINE INDENT if preSum [ r ] - preSum [ r ] [ c1 ] > 0 : NEW_LINE INDENT dp [ k ] [ r ] += dp [ k - 1 ] [ r ] [ c1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT return dp [ K ] [ 0 ] [ 0 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 0 , 0 ] , [ 1 , 1 , 1 ] , [ 0 , 0 , 0 ] ] NEW_LINE k = 3 NEW_LINE print ( ways ( arr , k ) ) NEW_LINE DEDENT