# Print all paths from top left to bottom right in a matrix with four moves allowed in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an mXn 2D matrix and we have to print all possible paths from top left to bottom right of matrix. For traversal, we can move in all four directions i.e. left, right, top, bottom.

Thought the moves right and top are rarely used but these can be beneficial sometimes.

Let’s take an example to understand the topic better :

Input:

1 3 5

2 8 9

Output:

1 -> 3 -> 5 -> 9
1 -> 3 -> 8 -> 9
1 -> 2 -> 8 -> 9

To solve this problem, we will move from one cell to other and print the path on going down and right. We will do this recursively for each cell in the matrix.

Let's see a program that implements the recursive algorithm -

## Example

Live Demo

#include<iostream>
using namespace std;
void printPathTPtoBR(int *mat, int i, int j, int m, int n, int *path, int pi) {
if (i == m - 1) {
for (int k = j; k < n; k++)
path[pi + k - j] = *((mat + i*n) + k);
for (int l = 0; l < pi + n - j; l++)
cout << path[l] << " ";
cout << endl;
return;
}
if (j == n - 1) {
for (int k = i; k < m; k++)
path[pi + k - i] = *((mat + k*n) + j);
for (int l = 0; l < pi + m - i; l++)
cout << path[l] << " ";
cout << endl;
return;
}
path[pi] = *((mat + i*n) + j);
printPathTPtoBR(mat, i+1, j, m, n, path, pi + 1);
printPathTPtoBR(mat, i, j+1, m, n, path, pi + 1);
}
void findPath(int *mat, int m, int n) {
int *path = new int[m+n];
printPathTPtoBR(mat, 0, 0, m, n, path, 0);
}
int main() {
int mat = {
{1, 2, 3},
{4, 5, 6}
};
cout<<"Path from top-left to bottom-rigth of matrix are :\n";
findPath(*mat, 2, 3);
return 0;
}

## Output

Path from top-left to bottom-rigth of matrix are :
1 4 5 6
1 2 5 6
1 2 3 6