Given an n x m matrix mat[][], where each cell contains an integer, return all possible paths from the top-left cell (0, 0) to the bottom-right cell (n - 1, m - 1). From each cell, you can move only:
- Right to (i, j + 1)
- Down to (i + 1, j)
Each path should be represented as a list of the matrix elements encountered along the path. Return all such possible paths in any order.
Examples :
Input: mat[][] = [[1, 2, 3], [4, 5, 6]]
Output: [[1, 4, 5, 6], [1, 2, 5, 6], [1, 2, 3, 6]]
Explanation: There are 3 possible paths from the top-left cell to the bottom-right cell.Input: mat[][] = [[1, 2], [3, 4]]
Output: [[1, 2, 4], [1, 3, 4]]
Explanation: There are 2 possible paths from the top-left cell to the bottom-right cell.
Using Backtracking- O((n + m) × C(n + m - 2, n - 1))Time and O(n + m) Space
The idea is to explore all possible paths from the top-left cell to the bottom-right cell using recursion. At each cell, include the current element in the path and recursively move either right or down. When the destination cell is reached, the current path represents one valid path. Backtracking is used to remove the current cell from the path after exploring all possible moves, allowing other paths to be explored.
Steps:
- Start from the top-left cell (0, 0)
- Add the current cell value to the path
- If the current cell is the bottom-right cell, print the path and return
- Otherwise, recursively move to the right cell (i, j+1) if valid
- Recursively move to the down cell (i+1, j) if valid
- Backtrack by removing the current cell from the path before returning
#include <iostream>
#include <vector>
using namespace std;
// Recursive function to find all possible paths
void findPaths(vector<vector<int>> &mat, int i, int j,
vector<int> &path, vector<vector<int>> &paths) {
int n = mat.size(), m = mat[0].size();
path.push_back(mat[i][j]);
// Reached the bottom-right cell
if (i == n - 1 && j == m - 1) {
paths.push_back(path);
} else {
// Move right
if (j + 1 < m)
findPaths(mat, i, j + 1, path, paths);
// Move down
if (i + 1 < n)
findPaths(mat, i + 1, j, path, paths);
}
// Backtrack
path.pop_back();
}
// Function to return all possible paths
vector<vector<int>> allPaths(vector<vector<int>> &mat) {
vector<vector<int>> paths;
vector<int> path;
findPaths(mat, 0, 0, path, paths);
return paths;
}
int main() {
vector<vector<int>> mat = {
{1, 2, 3},
{4, 5, 6}
};
vector<vector<int>> res = allPaths(mat);
cout << "[";
for (int i = 0; i < res.size(); i++) {
cout << "[";
for (int j = 0; j < res[i].size(); j++) {
cout << res[i][j];
if (j != res[i].size() - 1)
cout << ", ";
}
cout << "]";
if (i != res.size() - 1)
cout << ", ";
}
cout << "]";
return 0;
}
import java.util.ArrayList;
class GFG {
// Recursive function to find all possible paths
static void findPaths(int[][] mat, int i, int j,
ArrayList<Integer> path,
ArrayList<ArrayList<Integer>> paths) {
int n = mat.length, m = mat[0].length;
path.add(mat[i][j]);
// Reached the bottom-right cell
if (i == n - 1 && j == m - 1) {
paths.add(new ArrayList<>(path));
} else {
// Move right
if (j + 1 < m)
findPaths(mat, i, j + 1, path, paths);
// Move down
if (i + 1 < n)
findPaths(mat, i + 1, j, path, paths);
}
// Backtrack
path.remove(path.size() - 1);
}
// Function to return all possible paths
static ArrayList<ArrayList<Integer>> allPaths(int[][] mat) {
ArrayList<ArrayList<Integer>> paths = new ArrayList<>();
ArrayList<Integer> path = new ArrayList<>();
findPaths(mat, 0, 0, path, paths);
return paths;
}
public static void main(String[] args) {
int[][] mat = {
{1, 2, 3},
{4, 5, 6}
};
ArrayList<ArrayList<Integer>> res = allPaths(mat);
System.out.print("[");
for (int i = 0; i < res.size(); i++) {
System.out.print("[");
for (int j = 0; j < res.get(i).size(); j++) {
System.out.print(res.get(i).get(j));
if (j != res.get(i).size() - 1)
System.out.print(", ");
}
System.out.print("]");
if (i != res.size() - 1)
System.out.print(", ");
}
System.out.println("]");
}
}
# Recursive function to find all possible paths
def findPaths(mat, i, j, path, paths):
n, m = len(mat), len(mat[0])
path.append(mat[i][j])
# Reached the bottom-right cell
if i == n - 1 and j == m - 1:
paths.append(path[:])
else:
# Move right
if j + 1 < m:
findPaths(mat, i, j + 1, path, paths)
# Move down
if i + 1 < n:
findPaths(mat, i + 1, j, path, paths)
# Backtrack
path.pop()
# Function to return all possible paths
def allPaths(mat):
paths = []
path = []
findPaths(mat, 0, 0, path, paths)
return paths
if __name__ == "__main__":
mat = [
[1, 2, 3],
[4, 5, 6]
]
res = allPaths(mat)
print(res)
using System;
using System.Collections.Generic;
class GFG
{
// Recursive function to find all possible paths
static void findPaths(int[,] mat, int i, int j,
List<int> path,
List<List<int>> paths)
{
int n = mat.GetLength(0), m = mat.GetLength(1);
path.Add(mat[i, j]);
// Reached the bottom-right cell
if (i == n - 1 && j == m - 1)
{
paths.Add(new List<int>(path));
}
else
{
// Move right
if (j + 1 < m)
findPaths(mat, i, j + 1, path, paths);
// Move down
if (i + 1 < n)
findPaths(mat, i + 1, j, path, paths);
}
// Backtrack
path.RemoveAt(path.Count - 1);
}
// Function to return all possible paths
static List<List<int>> allPaths(int[,] mat)
{
List<List<int>> paths = new List<List<int>>();
List<int> path = new List<int>();
findPaths(mat, 0, 0, path, paths);
return paths;
}
static void Main()
{
int[,] mat =
{
{1, 2, 3},
{4, 5, 6}
};
List<List<int>> res = allPaths(mat);
Console.Write("[");
for (int i = 0; i < res.Count; i++)
{
Console.Write("[");
for (int j = 0; j < res[i].Count; j++)
{
Console.Write(res[i][j]);
if (j != res[i].Count - 1)
Console.Write(", ");
}
Console.Write("]");
if (i != res.Count - 1)
Console.Write(", ");
}
Console.WriteLine("]");
}
}
// Recursive function to find all possible paths
function findPaths(mat, i, j, path, paths) {
const n = mat.length, m = mat[0].length;
path.push(mat[i][j]);
// Reached the bottom-right cell
if (i === n - 1 && j === m - 1) {
paths.push([...path]);
} else {
// Move right
if (j + 1 < m)
findPaths(mat, i, j + 1, path, paths);
// Move down
if (i + 1 < n)
findPaths(mat, i + 1, j, path, paths);
}
// Backtrack
path.pop();
}
// Function to return all possible paths
function allPaths(mat) {
const paths = [];
const path = [];
findPaths(mat, 0, 0, path, paths);
return paths;
}
// Driver code
const mat = [
[1, 2, 3],
[4, 5, 6]
];
const res = allPaths(mat);
console.log(JSON.stringify(res));
Output
[[1, 2, 3, 6], [1, 2, 5, 6], [1, 4, 5, 6]]