Given a 2D matrix of dimension m✕n, the task is to print all the possible paths from the top left corner to the bottom right corner in a 2D matrix with the constraints that from each cell you can either move to right or down only.
Examples :
Input: [[1,2,3], [4,5,6]] Output: [[1,4,5,6], [1,2,5,6], [1,2,3,6]]
Input: [[1,2], [3,4]] Output: [[1,2,4], [1,3,4]]
Print all possible paths from top left to bottom right in matrix using Backtracking
Explore all the possible paths from a current cell using recursion and backtracking to reach bottom right cell.
Base cases: Check If the bottom right cell, print the current path .
Boundary cases: In case in we reach out of the matrix, return from it.
Otherwise, Include the current cell in the path
Make two recursive call:
Move right in the matrix
Move down in the matrix
Backtrack: Remove the current cell from the current path
Implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int M, N;
void printPath(vector<int>& path)
{
for (int i : path) {
cout << i << ", ";
}
cout << endl;
}
void findPaths(vector<vector<int> >& arr, vector<int>& path,
int i, int j)
{
if (i == M - 1 && j == N - 1) {
path.push_back(arr[i][j]);
printPath(path);
path.pop_back();
return;
}
if (i < 0 && i >= M && j < 0 && j >= N) {
return;
}
path.push_back(arr[i][j]);
if (j + 1 < N) {
findPaths(arr, path, i, j + 1);
}
if (i + 1 < M) {
findPaths(arr, path, i + 1, j);
}
path.pop_back();
}
int main()
{
vector<vector<int> > arr
= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
vector<int> path;
int i = 0, j = 0;
M = arr.size();
N = arr[0].size();
findPaths(arr, path, i, j);
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
public class MatrixPaths {
static int M, N;
static void printPath(List<Integer> path) {
for (int i : path) {
System.out.print(i + ", ");
}
System.out.println();
}
static void findPaths(int[][] arr, List<Integer> path, int i, int j) {
if (i == M - 1 && j == N - 1) {
path.add(arr[i][j]);
printPath(path);
path.remove(path.size() - 1);
return;
}
if (i < 0 || i >= M || j < 0 || j >= N) {
return;
}
path.add(arr[i][j]);
if (j + 1 < N) {
findPaths(arr, path, i, j + 1);
}
if (i + 1 < M) {
findPaths(arr, path, i + 1, j);
}
path.remove(path.size() - 1);
}
public static void main(String[] args) {
int[][] arr = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
List<Integer> path = new ArrayList<>();
int i = 0, j = 0;
M = arr.length;
N = arr[0].length;
findPaths(arr, path, i, j);
}
}
Python3
def printPath(path):
for i in path:
print(i, end=", ")
print()
def findPaths(arr, path, i, j):
global M, N
if i == M - 1 and j == N - 1:
path.append(arr[i][j])
printPath(path)
path.pop()
return
if i < 0 or i >= M or j < 0 or j >= N:
return
path.append(arr[i][j])
if j + 1 < N:
findPaths(arr, path, i, j + 1)
if i + 1 < M:
findPaths(arr, path, i + 1, j)
path.pop()
if __name__ == "__main__":
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
path = []
i, j = 0, 0
M = len(arr)
N = len(arr[0])
findPaths(arr, path, i, j)
C#
using System;
using System.Collections.Generic;
class Program
{
static int M, N;
static void PrintPath(List<int> path)
{
foreach (int i in path)
{
Console.Write(i + ", ");
}
Console.WriteLine();
}
static void FindPaths(int[][] arr, List<int> path, int i, int j)
{
if (i == M - 1 && j == N - 1)
{
path.Add(arr[i][j]);
PrintPath(path);
path.RemoveAt(path.Count - 1);
return;
}
if (i < 0 || i >= M || j < 0 || j >= N)
{
return;
}
path.Add(arr[i][j]);
if (j + 1 < N)
{
FindPaths(arr, path, i, j + 1);
}
if (i + 1 < M)
{
FindPaths(arr, path, i + 1, j);
}
path.RemoveAt(path.Count - 1);
}
static void Main(string[] args)
{
int[][] arr = {
new int[] { 1, 2, 3 },
new int[] { 4, 5, 6 },
new int[] { 7, 8, 9 }
};
List<int> path = new List<int>();
int i = 0, j = 0;
M = arr.Length;
N = arr[0].Length;
FindPaths(arr, path, i, j);
}
}
Javascript
function printPath(path) {
for (let i = 0; i < path.length; i++) {
process.stdout.write(path[i] + ", ");
}
console.log();
}
function findPaths(arr, path, i, j) {
if (i === M - 1 && j === N - 1) {
path.push(arr[i][j]);
printPath(path);
path.pop();
return;
}
if (i < 0 || i >= M || j < 0 || j >= N) {
return;
}
path.push(arr[i][j]);
if (j + 1 < N) {
findPaths(arr, path, i, j + 1);
}
if (i + 1 < M) {
findPaths(arr, path, i + 1, j);
}
path.pop();
}
const arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const path = [];
let i = 0, j = 0;
const M = arr.length;
const N = arr[0].length;
findPaths(arr, path, i, j);
Output
1, 2, 3, 6, 9,
1, 2, 5, 6, 9,
1, 2, 5, 8, 9,
1, 4, 5, 6, 9,
1, 4, 5, 8, 9,
1, 4, 7, 8, 9,
Time Complexity : O(2^(N*M)) Auxiliary space : O(N + M), where M and N are dimension of matrix.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
07 Nov, 2023
Like Article
Save Article