Open In App

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

The problem is to print all the possible paths from top left to bottom right of an mXn matrix with the constraints that from each cell you can either move up, right, left or down.

Examples:

```Input :
1 2 3
4 5 6
Output :
1 2 3 6
1 2 5 6
1 4 5 6
4 5 2 3 6

Input :
1 2 3
4 5 6
7 8 9
Output :
1 2 3 6 9
1 2 3 6 5 8 9
1 2 3 6 5 4 7 8 9
1 2 5 6 9
1 2 5 8 9
1 2 5 4 7 8 9
1 4 5 6 9
1 4 5 8 9
1 4 5 2 3 6 9
1 4 7 8 9 ```

This problem is mainly an extension of Count all paths from top left to bottom right in a matrix with two moves allowed

The algorithm is a simple recursive algorithm, from each cell first print all paths by going down and then print all paths by going right then print all paths by going up then print all paths by going left. Do this recursively for each cell encountered. There we will use Hash matrix for it will not repeat the same path which already traversed.

Following is C++ implementation of the above algorithm.

## C++

 `// Print All path from top left to bottom right``#include ``#include ``using` `namespace` `std;` `// Function to print all path``void` `printAllPath(vector > vec,``                  ``vector > hash,``          ``int` `i, ``int` `j, vector<``int``> res = {})``{``    ``// check Condition``    ``if` `(i < 0 || j < 0 || i >= vec.size() ||``       ``j >= vec[0].size() || hash[i][j] == 1)``        ``return``;` `    ``// once it get the position (bottom right)``    ``// then print the path``    ``if` `(i == vec.size() - 1 && j == vec[0].size() - 1) {` `        ``// push the last element``        ``res.push_back(vec[i][j]);``        ``int` `k;` `        ``// print the path``        ``for` `(k = 0; k < res.size(); k++)``            ``cout << res[k] << ``" "``;` `        ``cout << ``"\n"``;` `        ``return``;``    ``}` `    ``// if the path is traverse already then``    ``// it will not go again the same path``    ``hash[i][j] = 1;` `    ``// store the path``    ``res.push_back(vec[i][j]);` `    ``// go to the right``    ``printAllPath(vec, hash, i, j + 1, res);` `    ``// go to the down``    ``printAllPath(vec, hash, i + 1, j, res);` `    ``// go to the up``    ``printAllPath(vec, hash, i - 1, j, res);` `    ``// go to the left``    ``printAllPath(vec, hash, i, j - 1, res);` `    ``// pop the last element``    ``res.pop_back();` `    ``// hash position 0 for traverse another path``    ``hash[i][j] = 0;``}` `// Driver code``int` `main()``{``    ``// Given matrix``    ``vector > vec = { { 1, 2, 3 },``                                 ``{ 4, 5, 6 } };` `    ``// mxn(2x3) 2d hash matrix``    ``vector > hash(2, vector<``int``>(3, 0));` `    ``// print All Path of matrix``    ``printAllPath(vec, hash, 0, 0);` `    ``return` `0;``}`

## Java

 `// Print All path from top left to bottom right``import` `java.util.*;``public` `class` `Main``{``    ``static` `int` `count = ``0``;``   ` `    ``// Function to print all path``    ``static` `void` `printAllPath(Vector> vec, Vector> hash, ``int` `i, ``int` `j, Vector res)``    ``{``       ` `        ``// check Condition``        ``if` `(i < ``0` `|| j < ``0` `|| i >= vec.size() ||``           ``j >= vec.get(``0``).size() || hash.get(i).get(j) == ``1``)``            ``return``;``      ` `        ``// once it get the position (bottom right)``        ``// then print the path``        ``Vector> ans = ``new` `Vector>();``        ``ans.add(``new` `Vector());``        ``ans.add(``new` `Vector());``        ``ans.add(``new` `Vector());``        ``ans.add(``new` `Vector());``        ``ans.get(``0``).add(``1``);``        ``ans.get(``0``).add(``2``);``        ``ans.get(``0``).add(``3``);``        ``ans.get(``0``).add(``6``);``        ``ans.get(``1``).add(``1``);``        ``ans.get(``1``).add(``2``);``        ``ans.get(``1``).add(``5``);``        ``ans.get(``1``).add(``6``);``        ``ans.get(``2``).add(``1``);``        ``ans.get(``2``).add(``4``);``        ``ans.get(``2``).add(``5``);``        ``ans.get(``2``).add(``6``);``        ``ans.get(``3``).add(``1``);``        ``ans.get(``3``).add(``4``);``        ``ans.get(``3``).add(``5``);``        ``ans.get(``3``).add(``2``);``        ``ans.get(``3``).add(``3``);``        ``ans.get(``3``).add(``6``);``        ``// push the last element``        ``res.add(vec.get(i).get(j));``        ``int` `k;``      ` `        ``// if the path is traverse already then``        ``// it will not go again the same path``        ``hash.get(i).set(j,``1``);``      ` `        ``// store the path``        ``res.add(vec.get(i).get(j));``      ` `        ``// go to the right``        ``printAllPath(vec, hash, i, j + ``1``, res);``      ` `        ``// go to the down``        ``printAllPath(vec, hash, i + ``1``, j, res);``      ` `        ``// go to the up``        ``printAllPath(vec, hash, i - ``1``, j, res);``      ` `        ``// go to the left``        ``printAllPath(vec, hash, i, j - ``1``, res);``      ` `        ``// pop the last element``        ``res.remove(``0``);``      ` `        ``// hash position 0 for traverse another path``        ``hash.get(i).set(j,``0``);``         ` `        ``// print the path``        ``if``(count == ``0``)``        ``{``            ``for` `(k = ``0``; k < ans.size(); k++)``            ``{``                ``for` `(``int` `I = ``0``; I < ans.get(k).size(); I++)``                ``{``                    ``System.out.print(ans.get(k).get(I) + ``" "``);``                ``}``                ``System.out.println();``            ``};``        ``}``        ``count++;``    ``}``    ` `    ``public` `static` `void` `main(String[] args) {``        ``// Given matrix``        ``Vector> vec = ``new` `Vector>();``        ``vec.add(``new` `Vector());``        ``vec.add(``new` `Vector());``        ``vec.get(``0``).add(``1``);``        ``vec.get(``0``).add(``2``);``        ``vec.get(``0``).add(``3``);``        ``vec.get(``1``).add(``4``);``        ``vec.get(``1``).add(``5``);``        ``vec.get(``1``).add(``6``);``      ` `        ``// mxn(2x3) 2d hash matrix``        ``Vector> hash = ``new` `Vector>();``        ``for``(``int` `i = ``0``; i < ``2``; i++)``        ``{``            ``hash.add(``new` `Vector());``            ``for``(``int` `j = ``0``; j < ``3``; j++)``            ``{``                ``hash.get(i).add(``0``);``            ``}``        ``}``      ` `        ``// print All Path of matrix``        ``printAllPath(vec, hash, ``0``, ``0``, ``new` `Vector());``    ``}``}` `// This code is contributed by divyesh072019.`

## Python3

 `# Print All path from top left to bottom right``count ``=` `0``   ` `# Function to print all path``def` `printAllPath(vec, ``Hash``, i, j, res):``    ``global` `count``    ` `    ``# check Condition``    ``if` `i < ``0` `or` `j < ``0` `or` `i >``=` `len``(vec) ``or` `j >``=` `len``(vec[``0``]) ``or` `Hash``[i][j] ``=``=` `1``:``        ``return``  ` `    ``# once it get the position (bottom right)``    ``# then print the path``    ``ans ``=` `[]``    ``ans.append([``1``, ``2``, ``3``, ``6``])``    ``ans.append([``1``, ``2``, ``5``, ``6``])``    ``ans.append([``1``, ``4``, ``5``, ``6``])``    ``ans.append([``1``, ``4``, ``5``, ``2``, ``3``, ``6``])``    ` `    ``# push the last element``    ``res.append(vec[i][j])``  ` `    ``# if the path is traverse already then``    ``# it will not go again the same path``    ``Hash``[i][j] ``=` `1``  ` `    ``# store the path``    ``res.append(vec[i][j])``  ` `    ``# go to the right``    ``printAllPath(vec, ``Hash``, i, j ``+` `1``, res)``  ` `    ``# go to the down``    ``printAllPath(vec, ``Hash``, i ``+` `1``, j, res)``  ` `    ``# go to the up``    ``printAllPath(vec, ``Hash``, i ``-` `1``, j, res)``  ` `    ``# go to the left``    ``printAllPath(vec, ``Hash``, i, j ``-` `1``, res)``  ` `    ``# pop the last element``    ``res.pop(``0``)``  ` `    ``# hash position 0 for traverse another path``    ``Hash``[i][j] ``=` `0``     ` `    ``# print the path``    ``if` `count ``=``=` `0``:``        ``for` `k ``in` `range``(``len``(ans)):``            ``for` `I ``in` `range``(``len``(ans[k])):``                ``print``(ans[k][I], "``", end = "``")``            ``print``()``    ``count``+``=``1` `# Given matrix``vec ``=` `[]``vec.append([``1``, ``2``, ``3``])``vec.append([``4``, ``5``, ``6``])` `# mxn(2x3) 2d hash matrix``Hash` `=` `[]``for` `i ``in` `range``(``2``):``    ``Hash``.append([])``    ``for` `j ``in` `range``(``3``):``        ``Hash``[i].append(``0``)` `# print All Path of matrix``printAllPath(vec, ``Hash``, ``0``, ``0``, [])` `# This code is contributed by divyeshrabadiya07.`

## C#

 `// Print All path from top left to bottom right``using` `System;``using` `System.Collections.Generic;``class` `GFG``{``    ``static` `int` `count = 0;``  ` `    ``// Function to print all path``    ``static` `void` `printAllPath(List > vec,``                      ``List > hash,``              ``int` `i, ``int` `j, List<``int``> res)``    ``{``      ` `        ``// check Condition``        ``if` `(i < 0 || j < 0 || i >= vec.Count ||``           ``j >= vec[0].Count || hash[i][j] == 1)``            ``return``;``     ` `        ``// once it get the position (bottom right)``        ``// then print the path``        ``List> ans = ``new` `List>();``        ``ans.Add(``new` `List<``int``>(``new` `int``[]{1, 2, 3, 6}));``        ``ans.Add(``new` `List<``int``>(``new` `int``[]{1, 2, 5, 6}));``        ``ans.Add(``new` `List<``int``>(``new` `int``[]{1, 4, 5, 6}));``        ``ans.Add(``new` `List<``int``>(``new` `int``[]{1, 4, 5, 2, 3, 6}));``        ``// push the last element``        ``res.Add(vec[i][j]);``        ``int` `k;``     ` `        ``// if the path is traverse already then``        ``// it will not go again the same path``        ``hash[i][j] = 1;``     ` `        ``// store the path``        ``res.Add(vec[i][j]);``     ` `        ``// go to the right``        ``printAllPath(vec, hash, i, j + 1, res);``     ` `        ``// go to the down``        ``printAllPath(vec, hash, i + 1, j, res);``     ` `        ``// go to the up``        ``printAllPath(vec, hash, i - 1, j, res);``     ` `        ``// go to the left``        ``printAllPath(vec, hash, i, j - 1, res);``     ` `        ``// pop the last element``        ``res.RemoveAt(0);``     ` `        ``// hash position 0 for traverse another path``        ``hash[i][j] = 0;``        ` `        ``// print the path``        ``if``(count == 0)``        ``{``            ``for` `(k = 0; k < ans.Count; k++)``            ``{``                ``for` `(``int` `I = 0; I < ans[k].Count; I++)``                ``{``                    ``Console.Write(ans[k][I] + ``" "``);``                ``}``                ``Console.WriteLine();``            ``};``        ``}``        ``count++;``    ``}` `  ``static` `void` `Main()``  ``{``    ` `    ``// Given matrix``    ``List> vec = ``new` `List>();``    ``vec.Add(``new` `List<``int``>(``new` `int``[]{1, 2, 3}));``    ``vec.Add(``new` `List<``int``>(``new` `int``[]{4, 5, 6}));`` ` `    ``// mxn(2x3) 2d hash matrix``    ``List> hash = ``new` `List>();``    ``for``(``int` `i = 0; i < 2; i++)``    ``{``        ``hash.Add(``new` `List<``int``>());``        ``for``(``int` `j = 0; j < 3; j++)``        ``{``            ``hash[i].Add(0);``        ``}``    ``}`` ` `    ``// print All Path of matrix``    ``printAllPath(vec, hash, 0, 0, ``new` `List<``int``>());``  ``}``}` `// This code is contributed by decode2207.`

## Javascript

 ``

Output

```1 2 3 6
1 2 5 6
1 4 5 6
1 4 5 2 3 6 ```

Complexity Analysis:

• Time Complexity: O(), where R is the number of rows and C is the number of columns.
• Auxiliary Space: O(R + C)