# Python program for the above approach
def backtrack(mat, row, col, currentPath, currentSum, S):
# Base case: if out of bounds, return
if row >= len(mat) or col >= len(mat[0]):
return
# Add the current element to the path and sum
currentPath.append(mat[row][col])
currentSum += mat[row][col]
# If we reached the target sum and it's the bottom-right cell, print the path
if currentSum == S:
# Print the current path
print(" -> ".join(map(str, currentPath)))
# Explore moving right
backtrack(mat, row, col + 1, currentPath, currentSum, S)
# Explore moving down
backtrack(mat, row + 1, col, currentPath, currentSum, S)
# Backtrack: remove the last element to explore other paths
currentPath.pop()
def findPaths(matrix, targetSum, path):
backtrack(matrix, 0, 0, path, 0, targetSum)
# Driver's code
if __name__ == "__main__":
mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# target sum
S = 12
path = []
# Function call
findPaths(mat, S, path)
# This code is contributed by Susobhan Akhuli