Banana-Leopard/TASTY huggingface dataset:
# A Python3 program to count the number
# of rectangular islands where every
# island is separated by a line
 
# Size of given matrix is M X N
M = 6
N = 3
 
# This function takes a matrix of 'X' and 'O'
# and returns the number of rectangular
# islands of 'X' where no two islands are
# row-wise or column-wise adjacent, the islands
# may be diagonally adjacent
def countIslands(mat):
 
    count = 0; # Initialize result
 
    # Traverse the input matrix
    for i in range (0, M):
     
        for j in range(0, N):
         
            # If current cell is 'X', then check
            # whether this is top-leftmost of a
            # rectangle. If yes, then increment count
            if (mat[i][j] == 'X'):
             
                if ((i == 0 or mat[i - 1][j] == 'O') and
                    (j == 0 or mat[i][j - 1] == 'O')):
                    count = count + 1
             
    return count
 
# Driver Code
mat = [['O', 'O', 'O'],
       ['X', 'X', 'O'],
       ['X', 'X', 'O'],
       ['O', 'O', 'X'],
       ['O', 'O', 'X'],
       ['X', 'X', 'O']]
                 
print("Number of rectangular islands is",
                       countIslands(mat))
 
# This code is contributed by iAyushRaj

Time complexity: quadratic
Space complexity: constant
# Python 3 program to find a common element
# in all rows of a row wise sorted array
 
# Specify number of rows
# and columns
M = 4
N = 5
 
# Returns common element in all rows
# of mat[M][N]. If there is no common
# element, then -1 is returned
def findCommon(mat):
 
    # An array to store indexes of
    # current last column
    column = [N - 1] * M
 
    min_row = 0 # Initialize min_row as first row
 
    # Keep finding min_row in current last
    # column, till either all elements of
    # last column become same or we hit first column.
    while (column[min_row] >= 0):
     
        # Find minimum in current last column
        for i in range(M):
            if (mat[i][column[i]] <
                mat[min_row][column[min_row]]):
                min_row = i
     
        # eq_count is count of elements equal
        # to minimum in current last column.
        eq_count = 0
 
        # Traverse current last column elements
        # again to update it
        for i in range(M):
             
            # Decrease last column index of a row
            # whose value is more than minimum.
            if (mat[i][column[i]] >
                mat[min_row][column[min_row]]):
                if (column[i] == 0):
                    return -1
 
                column[i] -= 1 # Reduce last column
                               # index by 1
         
            else:
                eq_count += 1
 
        # If equal count becomes M, return the value
        if (eq_count == M):
            return mat[min_row][column[min_row]]
    return -1
 
# Driver Code
if __name__ == "__main__":
     
    mat = [[1, 2, 3, 4, 5],
           [2, 4, 5, 8, 10],
           [3, 5, 7, 9, 11],
           [1, 3, 5, 7, 9]]
 
    result = findCommon(mat)
    if (result == -1):
        print("No common element")
    else:
        print("Common element is", result)
 
# This code is contributed by ita_c

Time complexity: quadratic
Space complexity: linear
# Python3 program to replace all 'O's with
# 'X's if surrounded by 'X'
 
# Size of given matrix is M x N
M = 6
N = 6
 
# A recursive function to replace previous
# value 'prevV' at '(x, y)' and all surrounding
# values of (x, y) with new value 'newV'.
def floodFillUtil(mat, x, y, prevV, newV):
 
    # Base Cases
    if (x < 0 or x >= M or y < 0 or y >= N):
        return
 
    if (mat[x][y] != prevV):
        return
 
    # Replace the color at (x, y)
    mat[x][y] = newV
 
    # Recur for north, east, south and west
    floodFillUtil(mat, x + 1, y, prevV, newV)
    floodFillUtil(mat, x - 1, y, prevV, newV)
    floodFillUtil(mat, x, y + 1, prevV, newV)
    floodFillUtil(mat, x, y - 1, prevV, newV)
 
# Returns size of maximum size subsquare
#  matrix surrounded by 'X'
def replaceSurrounded(mat):
 
    # Step 1: Replace all 'O's with '-'
    for i in range(M):
        for j in range(N):
            if (mat[i][j] == 'O'):
                mat[i][j] = '-'
 
    # Call floodFill for all '-'
    # lying on edges
     # Left Side
    for i in range(M):
        if (mat[i][0] == '-'):
            floodFillUtil(mat, i, 0, '-', 'O')
     
    # Right side
    for i in range(M):
        if (mat[i][N - 1] == '-'):
            floodFillUtil(mat, i, N - 1, '-', 'O')
     
    # Top side
    for i in range(N):
        if (mat[0][i] == '-'):
            floodFillUtil(mat, 0, i, '-', 'O')
     
    # Bottom side
    for i in range(N):
        if (mat[M - 1][i] == '-'):
            floodFillUtil(mat, M - 1, i, '-', 'O')
 
    # Step 3: Replace all '-' with 'X'
    for i in range(M):
        for j in range(N):
            if (mat[i][j] == '-'):
                mat[i][j] = 'X'
 
# Driver code
if __name__ == '__main__':
 
    mat = [ [ 'X', 'O', 'X', 'O', 'X', 'X' ],
            [ 'X', 'O', 'X', 'X', 'O', 'X' ],
            [ 'X', 'X', 'X', 'O', 'X', 'X' ],
            [ 'O', 'X', 'X', 'X', 'X', 'X' ],
            [ 'X', 'X', 'X', 'O', 'X', 'O' ],
            [ 'O', 'O', 'X', 'O', 'O', 'O' ] ];
 
    replaceSurrounded(mat)
 
    for i in range(M):
        print(*mat[i])
 
# This code is contributed by himanshu77

Time complexity: quadratic
Space complexity: quadratic
# A Python3 program to find the largest
# subsquare surrounded by 'X' in a given
# matrix of 'O' and 'X'
import math as mt
 
# Size of given matrix is N X N
N = 6
 
# A utility function to find minimum
# of two numbers
 
 
def getMin(x, y):
    if x < y:
        return x
    else:
        return y
 
# Returns size of Maximum size
# subsquare matrix surrounded by 'X'
 
 
def findSubSquare(mat):
 
    Max = 0  # Initialize result
 
    # Initialize the left-top value
    # in hor[][] and ver[][]
    hor = [[0 for i in range(N)]
           for i in range(N)]
    ver = [[0 for i in range(N)]
           for i in range(N)]
 
    if mat[0][0] == 'X':
        hor[0][0] = 1
        ver[0][0] = 1
 
    # Fill values in hor[][] and ver[][]
    for i in range(N):
 
        for j in range(N):
 
            if (mat[i][j] == 'O'):
                ver[i][j], hor[i][j] = 0, 0
            else:
                if j == 0:
                    ver[i][j], hor[i][j] = 1, 1
                else:
                    (ver[i][j],
                     hor[i][j]) = (ver[i - 1][j] + 1,
                                   hor[i][j - 1] + 1)
 
    # Start from the rightmost-bottommost corner
    # element and find the largest ssubsquare
    # with the help of hor[][] and ver[][]
    for i in range(N - 1, 0, -1):
 
        for j in range(N - 1, 0, -1):
 
            # Find smaller of values in hor[][] and
            # ver[][]. A Square can only be made by
            # taking smaller value
            small = getMin(hor[i][j], ver[i][j])
 
            # At this point, we are sure that there
            # is a right vertical line and bottom
            # horizontal line of length at least 'small'.
 
            # We found a bigger square if following
            # conditions are met:
            # 1)If side of square is greater than Max.
            # 2)There is a left vertical line
            #   of length >= 'small'
            # 3)There is a top horizontal line
            #   of length >= 'small'
            while (small > Max):
 
                if (ver[i][j - small + 1] >= small and
                        hor[i - small + 1][j] >= small):
 
                    Max = small
 
                small -= 1
 
    return Max
 
 
# Driver Code
mat = [['X', 'O', 'X', 'X', 'X', 'X'],
       ['X', 'O', 'X', 'X', 'O', 'X'],
       ['X', 'X', 'X', 'O', 'O', 'X'],
       ['O', 'X', 'X', 'X', 'X', 'X'],
       ['X', 'X', 'X', 'O', 'X', 'O'],
       ['O', 'O', 'X', 'O', 'O', 'O']]
 
# Function call
print(findSubSquare(mat))
 
# This code is contributed by
# Mohit kumar 29

Time complexity: quadratic
Space complexity: quadratic
# Python3 program to find  the largest
# subsquare surrounded by 'X' in a given
# matrix of 'O' and 'X'
 
# Size of given matrix is N X N
N = 6
 
def maximumSubSquare(arr):
     
    dp = [[[-1, -1] for i in range(51)]
                    for j in range(51)]
 
    # Initialize maxside with 0
    maxside = [[0 for i in range(51)]
                  for j in range(51)]
                   
    x = 0
    y = 0
     
    # Fill the dp matrix horizontally.
    # for contiguous 'X' increment the
    # value of x, otherwise make it 0
    for i in range(N):
        x = 0
         
        for j in range(N):
            if (arr[i][j] == 'X'):
                x += 1
            else:
                x = 0
                 
            dp[i][j][0] = x
 
    # Fill the dp matrix vertically.
    # For contiguous 'X' increment
    # the value of y, otherwise
    # make it 0
    for i in range(N):
      y = 0
        for j in range(N):
            if (arr[j][i] == 'X'):
                y += 1
            else:
                y = 0
                 
            dp[j][i][1] = y
     
    # Now check , for every value of (i, j) if sub-square
    # is possible,
    # traverse back horizontally by value val, and check if
    # vertical contiguous
    # 'X'enfing at (i , j-val+1) is greater than equal to
    # val.
    # Similarly, check if traversing back vertically, the
    # horizontal contiguous
    # 'X'ending at (i-val+1, j) is greater than equal to
    # val.
    maxval = 0
    val = 0
 
    for i in range(N):
        for j in range(N):
            val = min(dp[i][j][0],
                      dp[i][j][1])
                       
            if (dp[i][j - val + 1][1] >= val and
                dp[i - val + 1][j][0] >= val):
                maxside[i][j] = val
            else:
                maxside[i][j] = 0
 
            # Store the final answer in maxval
            maxval = max(maxval, maxside[i][j])
 
    # Return the final answe.
    return maxval
 
# Driver code
mat = [ [ 'X', 'O', 'X', 'X', 'X', 'X' ],
        [ 'X', 'O', 'X', 'X', 'O', 'X' ],
        [ 'X', 'X', 'X', 'O', 'O', 'X' ],
        [ 'O', 'X', 'X', 'X', 'X', 'X' ],
        [ 'X', 'X', 'X', 'O', 'X', 'O' ],
        [ 'O', 'O', 'X', 'O', 'O', 'O' ] ]
         
# Function call
print(maximumSubSquare(mat))
 
# This code is contributed by avanitrachhadiya2155

Time complexity: quadratic
Space complexity: quadratic
# Python3 program to implement
# flood fill algorithm
 
# Dimensions of paint screen
M = 8
N = 8
 
# A recursive function to replace
# previous color 'prevC' at '(x, y)'
# and all surrounding pixels of (x, y)
# with new color 'newC' and
def floodFillUtil(screen, x, y, prevC, newC):
     
    # Base cases
    if (x < 0 or x >= M or y < 0 or
        y >= N or screen[x][y] != prevC or
        screen[x][y] == newC):
        return
 
    # Replace the color at (x, y)
    screen[x][y] = newC
 
    # Recur for north, east, south and west
    floodFillUtil(screen, x + 1, y, prevC, newC)
    floodFillUtil(screen, x - 1, y, prevC, newC)
    floodFillUtil(screen, x, y + 1, prevC, newC)
    floodFillUtil(screen, x, y - 1, prevC, newC)
 
# It mainly finds the previous color on (x, y) and
# calls floodFillUtil()
def floodFill(screen, x, y, newC):
    prevC = screen[x][y]
    if(prevC==newC):
      return
    floodFillUtil(screen, x, y, prevC, newC)
 
# Driver Code
screen = [[1, 1, 1, 1, 1, 1, 1, 1],
          [1, 1, 1, 1, 1, 1, 0, 0],
          [1, 0, 0, 1, 1, 0, 1, 1],
          [1, 2, 2, 2, 2, 0, 1, 0],
          [1, 1, 1, 2, 2, 0, 1, 0],
          [1, 1, 1, 2, 2, 2, 2, 0],
          [1, 1, 1, 1, 1, 2, 1, 1],
          [1, 1, 1, 1, 1, 2, 2, 1]]
 
x = 4
y = 4
newC = 3
floodFill(screen, x, y, newC)
 
print ("Updated screen after call to floodFill:")
for i in range(M):
    for j in range(N):
        print(screen[i][j], end = ' ')
    print()
 
# This code is contributed by Ashutosh450
# Updated by Arun Pandey

Time complexity: quadratic
Space complexity: quadratic
# Python3 program for above approach
 
# Function to check valid coordinate
def validCoord(x, y, n, m):
    if x < 0 or y < 0:
        return 0
    if x >= n or y >= m:
        return 0
    return 1
 
# Function to run bfs
def bfs(n, m, data, X, Y, color):
   
  # Visiting array
  vis = [[0 for i in range(101)] for j in range(101)]
     
  # Creating queue for bfs
  obj = []
     
  # Pushing pair of {x, y}
  obj.append([X, Y])
     
  # Marking {x, y} as visited
  vis[X][Y] = 1
     
  # Until queue is empty
  while len(obj) > 0:
     
    # Extracting front pair
    coord = obj[0]
    x = coord[0]
    y = coord[1]
    preColor = data[x][y]
   
    data[x][y] = color
       
    # Popping front pair of queue
    obj.pop(0)
   
    # For Upside Pixel or Cell
    if validCoord(x + 1, y, n, m) == 1 and vis[x + 1][y] == 0 and data[x + 1][y] == preColor:
      obj.append([x + 1, y])
      vis[x + 1][y] = 1
       
    # For Downside Pixel or Cell
    if validCoord(x - 1, y, n, m) == 1 and vis[x - 1][y] == 0 and data[x - 1][y] == preColor:
      obj.append([x - 1, y])
      vis[x - 1][y] = 1
       
    # For Right side Pixel or Cell
    if validCoord(x, y + 1, n, m) == 1 and vis[x][y + 1] == 0 and data[x][y + 1] == preColor:
      obj.append([x, y + 1])
      vis[x][y + 1] = 1
       
    # For Left side Pixel or Cell
    if validCoord(x, y - 1, n, m) == 1 and vis[x][y - 1] == 0 and data[x][y - 1] == preColor:
      obj.append([x, y - 1])
      vis[x][y - 1] = 1
     
  # Printing The Changed Matrix Of Pixels
  for i in range(n):
    for j in range(m):
      print(data[i][j], end = " ")
    print()
  print()
 
n = 8
m = 8
 
data = [
  [ 1, 1, 1, 1, 1, 1, 1, 1 ],
  [ 1, 1, 1, 1, 1, 1, 0, 0 ],
  [ 1, 0, 0, 1, 1, 0, 1, 1 ],
  [ 1, 2, 2, 2, 2, 0, 1, 0 ],
  [ 1, 1, 1, 2, 2, 0, 1, 0 ],
  [ 1, 1, 1, 2, 2, 2, 2, 0 ],
  [ 1, 1, 1, 1, 1, 2, 1, 1 ],
  [ 1, 1, 1, 1, 1, 2, 2, 1 ],
]
 
x, y, color = 4, 4, 3
 
# Function Call
bfs(n, m, data, x, y, color)
 
# This code is contributed by decode2207.

Time complexity: quadratic
Space complexity: quadratic
# A simple Python 3 program to find sum
# of all subsquares of size k x k
 
# Size of given matrix
n = 5
 
# A simple function to find sum of all
# sub-squares of size k x k in a given
# square matrix of size n x n
def printSumSimple(mat, k):
 
    # k must be smaller than or equal to n
    if (k > n):
        return
 
    # row number of first cell in current
    # sub-square of size k x k
    for i in range(n - k + 1):
     
        # column of first cell in current
        # sub-square of size k x k
        for j in range(n - k + 1):
             
            # Calculate and print sum of
            # current sub-square
            sum = 0
            for p in range(i, k + i):
                for q in range(j, k + j):
                    sum += mat[p][q]
            print(sum, end = " ")
     
        # Line separator for sub-squares
        # starting with next row
        print()
 
# Driver Code
if __name__ == "__main__":
 
    mat = [[1, 1, 1, 1, 1],
           [2, 2, 2, 2, 2],
           [3, 3, 3, 3, 3],
           [4, 4, 4, 4, 4],
           [5, 5, 5, 5, 5]]
    k = 3
    printSumSimple(mat, k)
 
# This code is contributed by ita_c

Time complexity: quadratic
Space complexity: constant
# An efficient Python3 program to find sum
# of all subsquares of size k x k
 
# A O(n^2) function to find sum of all 
# sub-squares of size k x k in a given
# square matrix of size n x n
def printSumTricky(mat, k):
    global n
     
    # k must be smaller than or
    # equal to n
    if k > n:
        return
 
    # 1: PREPROCESSING
    # To store sums of all strips of size k x 1
    stripSum = [[None] * n for i in range(n)]
 
    # Go column by column
    for j in range(n):
         
        # Calculate sum of first k x 1
        # rectangle in this column
        Sum = 0
        for i in range(k):
            Sum += mat[i][j]
        stripSum[0][j] = Sum
 
        # Calculate sum of remaining rectangles
        for i in range(1, n - k + 1):
            Sum += (mat[i + k - 1][j] -
                    mat[i - 1][j])
            stripSum[i][j] = Sum
 
    # 2: CALCULATE SUM of Sub-Squares
    # using stripSum[][]
    for i in range(n - k + 1):
         
        # Calculate and print sum of first
        # subsquare in this row
        Sum = 0
        for j in range(k):
            Sum += stripSum[i][j]
        print(Sum, end = " ")
 
        # Calculate sum of remaining squares
        # in current row by removing the leftmost 
        # strip of previous sub-square and adding
        # a new strip
        for j in range(1, n - k + 1):
            Sum += (stripSum[i][j + k - 1] -
                    stripSum[i][j - 1])
            print(Sum, end = " ")
 
        print()
 
# Driver Code
n = 5
mat = [[1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5]]
k = 3
printSumTricky(mat, k)
 
# This code is contributed by PranchalK

Time complexity: quadratic
Space complexity: quadratic
# Python3 Program to find
# transpose of a matrix
 
N = 4
 
# This function stores
# transpose of A[][] in B[][]
 
 
def transpose(A, B):
 
    for i in range(N):
        for j in range(N):
            B[i][j] = A[j][i]
 
 
# Driver code
if __name__ == '__main__':
  A = [[1, 1, 1, 1],
       [2, 2, 2, 2],
       [3, 3, 3, 3],
       [4, 4, 4, 4]]
 
 
  # To store result
  B = [[0 for x in range(N)] for y in range(N)]
 
  # Function call
  transpose(A, B)
 
  print("Result matrix is")
  for i in range(N):
      for j in range(N):
          print(B[i][j], " ", end='')
      print()

Time complexity: quadratic
Space complexity: quadratic
# Python3 Program to find
# transpose of a matrix
 
N = 4
 
# Finds transpose of A[][] in-place
 
 
def transpose(A):
 
    for i in range(N):
        for j in range(i+1, N):
            A[i][j], A[j][i] = A[j][i], A[i][j]
 
 
# driver code
A = [[1, 1, 1, 1],
     [2, 2, 2, 2],
     [3, 3, 3, 3],
     [4, 4, 4, 4]]
 
transpose(A)
 
print("Modified matrix is")
for i in range(N):
    for j in range(N):
        print(A[i][j], " ", end='')
    print()
 
# This code is contributed
# by Anant Agarwal.

Time complexity: quadratic
Space complexity: constant
# Python3 program for addition
# of two matrices
 
N = 4
 
# This function adds A[][]
# and B[][], and stores
# the result in C[][]
 
 
def add(A, B, C):
 
    for i in range(N):
        for j in range(N):
            C[i][j] = A[i][j] + B[i][j]
 
 
# driver code
A = [[1, 1, 1, 1],
     [2, 2, 2, 2],
     [3, 3, 3, 3],
     [4, 4, 4, 4]]
 
B = [[1, 1, 1, 1],
     [2, 2, 2, 2],
     [3, 3, 3, 3],
     [4, 4, 4, 4]]
 
C = A[:][:]  # To store result
 
add(A, B, C)
 
print("Result matrix is")
for i in range(N):
    for j in range(N):
        print(C[i][j], " ", end='')
    print()
 
# This code is contributed
# by Anant Agarwal.

Time complexity: quadratic
Space complexity: quadratic
# A Memoization based program to find maximum collection
# using two traversals of a grid
 
R=5
C=4
intmin=-10000000
intmax=10000000
 
# checks whether a given input is valid or not
def isValid(x,y1,y2):
    return ((x >= 0 and x < R and y1 >=0
            and y1 < C and y2 >=0 and y2 < C))
 
# Driver function to collect max value
def getMaxUtil(arr,mem,x,y1,y2):
    # ---------- BASE CASES -----------
    if isValid(x, y1, y2)==False:
        return intmin
         
    # if both traversals reach their destinations
    if x == R-1 and y1 == 0 and y2 == C-1:
        if y1==y2:
            return arr[x][y1]
        else:
            return arr[x][y1]+arr[x][y2]
             
    # If both traversals are at last row
    # but not at their destination
    if x==R-1:
        return intmin
         
    # If subproblem is already solved
    if mem[x][y1][y2] != -1:
        return mem[x][y1][y2]
         
    # Initialize answer for this subproblem
    ans=intmin
 
    # this variable is used to store gain of current cell(s)
    temp=0
    if y1==y2:
        temp=arr[x][y1]
    else:
        temp=arr[x][y1]+arr[x][y2]
         
    # Recur for all possible cases, then store and return the
    # one with max value
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1))
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1))
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2))
 
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2))
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1))
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1))
 
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2))
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1))
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1))
 
    mem[x][y1][y2] = ans
    return ans
 
# This is mainly a wrapper over recursive
# function getMaxUtil().
# This function creates a table for memoization and calls
# getMaxUtil()
 
def geMaxCollection(arr):
     
    # Create a memoization table and
    # initialize all entries as -1
    mem=[[[-1 for i in range(C)] for i in range(C)] for i in range(R)]
     
    # Calculation maximum value using
    # memoization based function
    # getMaxUtil()
    return getMaxUtil(arr, mem, 0, 0, C-1)
 
# Driver program to test above functions
if __name__=='__main__':
    arr=[[3, 6, 8, 2],
        [5, 2, 4, 3],
        [1, 1, 20, 10],
        [1, 1, 20, 10],
        [1, 1, 20, 10],
        ]
    print('Maximum collection is ', geMaxCollection(arr))
     
#this code is contributed by sahilshelangia

Time complexity: cubic
Space complexity: quadratic
# A Naive Recursive Python program to
# count paths with exactly 'k' coins
 
R = 3
C = 3
 
# Recursive function to count paths
# with sum k from (0, 0) to (m, n)
def pathCountRec(mat, m, n, k):
 
    # Base cases
    if m < 0 or n < 0 or k < 0:
        return 0
    elif m == 0 and n == 0:
        return k == mat[m][n]
 
    # #(m, n) can be reached either
    # through (m-1, n) or through
    # (m, n-1)
    return (pathCountRec(mat, m-1, n, k-mat[m][n])
         + pathCountRec(mat, m, n-1, k-mat[m][n]))
 
# A wrapper over pathCountRec()
def pathCount(mat, k):
    return pathCountRec(mat, R-1, C-1, k)
 
# Driver Program
k = 12
mat = [[1, 2, 3],
       [4, 6, 5],
       [3, 2, 1]]
 
print(pathCount(mat, k))
 
# This code is contributed by Shrikant13.

Time complexity: linear
Space complexity: quadratic
# A Dynamic Programming based Python3 program to
# count paths with exactly 'k' coins
R = 3
C = 3
MAX_K = 1000
 
def pathCountDPRecDP(mat, m, n, k):
 
    # Base cases
    if m < 0 or n < 0 or k < 0:
        return 0
    elif m == 0 and n == 0:
        return k == mat[m][n]
     
    # If this subproblem is already solved
    if (dp[m][n][k] != -1):
        return dp[m][n][k]
 
    # #(m, n) can be reached either
    # through (m-1, n) or through
    # (m, n-1)
    dp[m][n][k] = (pathCountDPRecDP(mat, m - 1, n, k - mat[m][n]) +
                   pathCountDPRecDP(mat, m, n - 1, k - mat[m][n]))
     
    return dp[m][n][k]
 
# A wrapper over pathCountDPRecDP()
def pathCountDP(mat, k):
    return pathCountDPRecDP(mat, R - 1, C - 1, k)
 
# Driver Code
k = 12
 
# Initialising dp[][][]
dp = [[ [-1 for col in range(MAX_K)]
            for col in range(C)]
            for row in range(R)]
 
mat = [[1, 2, 3],
       [4, 6, 5],
       [3, 2, 1]]
 
print(pathCountDP(mat, k))
 
# This code is contributed by ashutosh450

Time complexity: quadratic
Space complexity: quadratic