Print all paths in matrix with given target sum
Last Updated :
12 Mar, 2024
Given a 2D matrix mat[][] of size N*M and a target sum S, print all paths in matrix with sum = S from the top-left corner with the constraints that from each cell you can either move to right or down only.
Examples:
Input:S = 12mat[][] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output:
1 -> 2 -> 3 -> 61 -> 4 -> 7
Explanation: First path is: 1 -> 2 -> 3 -> 6 which sums 12. Second path is: 1 -> 4 -> 7 which sums 12
Input:
S = 16mat[][] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output:
1 -> 2 -> 5 -> 81 -> 4 -> 5 -> 6
Explanation: First path is: 1 -> 2 -> 5 -> 8 which sums 16. Second path is: 1 -> 4 -> 5 -> 6 which sums 16.
Approach: To solve the problem, follow the below idea:
The problem can be solved using Recursion to explore all the possible paths along with the running sum. At any point, if the path sum becomes equal to the target sum, we simply print the path and keep on exploring all the paths.
Step-by-step algorithm:
- Base case: If out of bounds, return.
- Add the current element to the path and update the current sum.
- If the target sum is reached, print the current path.
- Recursively explore moving right and down.
- Backtrack by removing the last element to explore other paths.
Below is the implementation of the above approach:
C++
// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the path using backtracking
void backtrack(vector<vector<int> >& mat, int row, int col,
vector<int>& current_path, int current_sum,
int S)
{
// Base case: if out of bounds, return
if (row >= mat.size() || col >= mat[0].size()) {
return;
}
// Add the current element to the path and sum
current_path.push_back(mat[row][col]);
current_sum += mat[row][col];
// If we reached the target sum and it's the
// bottom-right cell, print the path
if (current_sum == S) {
// Print the current path
for (int i = 0; i < current_path.size(); ++i) {
cout << current_path[i];
if (i < current_path.size() - 1) {
cout << " -> ";
}
}
cout << endl;
}
// Explore moving right
backtrack(mat, row, col + 1, current_path, current_sum,
S);
// Explore moving down
backtrack(mat, row + 1, col, current_path, current_sum,
S);
// Backtrack: remove the last element to explore other
// paths
current_path.pop_back();
}
// Function to find possible paths
void findPaths(vector<vector<int> >& matrix, int target_sum,
vector<int>& path)
{
backtrack(matrix, 0, 0, path, 0, target_sum);
}
// Driver's code
int main()
{
vector<vector<int> > mat
= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
// target sum
int S = 12;
vector<int> path;
// Function call
findPaths(mat, S, path);
return 0;
}
// This code is contributed by Susobhan Akhuli
Java
// Java program for the above approach
import java.util.ArrayList;
public class GFG {
// Function to find the path using backtracking
static void backtrack(int[][] mat, int row, int col,
ArrayList<Integer> currentPath,
int currentSum, int S)
{
// Base case: if out of bounds, return
if (row >= mat.length || col >= mat[0].length) {
return;
}
// Add the current element to the path and sum
currentPath.add(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
for (int i = 0; i < currentPath.size(); ++i) {
System.out.print(currentPath.get(i));
if (i < currentPath.size() - 1) {
System.out.print(" -> ");
}
}
System.out.println();
}
// 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.remove(currentPath.size() - 1);
}
// Function to find possible paths
static void findPaths(int[][] matrix, int targetSum,
ArrayList<Integer> path)
{
backtrack(matrix, 0, 0, path, 0, targetSum);
}
// Driver's code
public static void main(String[] args)
{
int[][] mat
= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
// target sum
int S = 12;
ArrayList<Integer> path = new ArrayList<>();
// Function call
findPaths(mat, S, path);
}
}
// This code is contributed by Susobhan Akhuli
C#
using System;
using System.Collections.Generic;
public class PathFinder
{
// Function to find the path using backtracking
static void Backtrack(List<List<int>> mat, int row, int col,
List<int> currentPath, int currentSum,
int targetSum)
{
// Base case: if out of bounds, return
if (row >= mat.Count || col >= mat[0].Count)
{
return;
}
// Add the current element to the path and sum
currentPath.Add(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 == targetSum)
{
// Print the current path
foreach (int num in currentPath)
{
Console.Write(num + " -> ");
}
Console.WriteLine();
}
// Explore moving right
Backtrack(mat, row, col + 1, currentPath, currentSum, targetSum);
// Explore moving down
Backtrack(mat, row + 1, col, currentPath, currentSum, targetSum);
// Backtrack: remove the last element to explore other
// paths
currentPath.RemoveAt(currentPath.Count - 1);
}
// Function to find possible paths
static void FindPaths(List<List<int>> matrix, int targetSum,
List<int> path)
{
Backtrack(matrix, 0, 0, path, 0, targetSum);
}
// Main method
public static void Main(string[] args)
{
List<List<int>> mat = new List<List<int>>
{
new List<int> {1, 2, 3},
new List<int> {4, 5, 6},
new List<int> {7, 8, 9}
};
// Target sum
int S = 12;
List<int> path = new List<int>();
// Function call
FindPaths(mat, S, path);
}
}
Javascript
// Function to find the path using backtracking
function backtrack(mat, row, col, currentPath, currentSum, S) {
// Base case: if out of bounds, return
if (row >= mat.length || col >= mat[0].length) {
return;
}
// Add the current element to the path and sum
currentPath.push(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
console.log(currentPath.join(" -> "));
}
// 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();
}
// Function to find possible paths
function findPaths(matrix, targetSum, path) {
backtrack(matrix, 0, 0, path, 0, targetSum);
}
// Driver's code
let mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// target sum
let S = 12;
let path = [];
// Function call
findPaths(mat, S, path);
Python3
# 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
Output1 -> 2 -> 3 -> 6
1 -> 4 -> 7
Time Complexity: O(2 ^ min(N, M)), where N is the number of rows and M is the number of columns.
Auxiliary Space: O(N + M)
Share your thoughts in the comments
Please Login to comment...