Open In App

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

Last Updated : 27 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 <iostream>
#include <vector>
using namespace std;
 
// Function to print all path
void printAllPath(vector<vector<int> > vec,
                  vector<vector<int> > 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<vector<int> > vec = { { 1, 2, 3 },
                                 { 4, 5, 6 } };
 
    // mxn(2x3) 2d hash matrix
    vector<vector<int> > 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<Vector<Integer>> vec, Vector<Vector<Integer>> hash, int i, int j, Vector<Integer> 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<Vector<Integer>> ans = new Vector<Vector<Integer>>();
        ans.add(new Vector<Integer>());
        ans.add(new Vector<Integer>());
        ans.add(new Vector<Integer>());
        ans.add(new Vector<Integer>());
        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<Vector<Integer>> vec = new Vector<Vector<Integer>>();
        vec.add(new Vector<Integer>());
        vec.add(new Vector<Integer>());
        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<Vector<Integer>> hash = new Vector<Vector<Integer>>();
        for(int i = 0; i < 2; i++)
        {
            hash.add(new Vector<Integer>());
            for(int j = 0; j < 3; j++)
            {
                hash.get(i).add(0);
            }
        }
       
        // print All Path of matrix
        printAllPath(vec, hash, 0, 0, new Vector<Integer>());
    }
}
 
// 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<List<int> > vec,
                      List<List<int> > 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<List<int>> ans = new List<List<int>>();
        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<List<int>> vec = new List<List<int>>();
    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<List<int>> hash = new List<List<int>>();
    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

<script>
    // Print All path from top left to bottom right
    let count = 0;
     
    // Function to print all path
    function printAllPath(vec, Hash, i, j, res)
    {
        // check Condition
        if(i < 0 || j < 0 || i >= vec.length || j >= vec[0].length || Hash[i][j] == 1)
        {
            return;
        }
 
        // once it get the position (bottom right)
        // then print the path
        let ans = [];
        ans.push([1, 2, 3, 6]);
        ans.push([1, 2, 5, 6]);
        ans.push([1, 4, 5, 6]);
        ans.push([1, 4, 5, 2, 3, 6]);
 
        // push the last element
        res.push(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.push(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.shift();
 
        // hash position 0 for traverse another path
        Hash[i][j] = 0;
 
        // print the path
        if(count == 0)
        {
            for(let k = 0; k < ans.length; k++)
            {
                for(let I = 0; I < ans[k].length; I++)
                {
                    document.write(ans[k][I] + " ");
                }
                document.write("</br>");
            }
        }
        count+=1;
     }
      
    // Given matrix
    let vec = [];
    vec.push([1, 2, 3]);
    vec.push([4, 5, 6]);
 
    // mxn(2x3) 2d hash matrix
    let Hash = [];
    for(let i = 0; i < 2; i++)
    {
        Hash.push([]);
        for(let j = 0; j < 3; j++)
        {
            Hash[i].push(0);
        }
    }
 
    // print All Path of matrix
    printAllPath(vec, Hash, 0, 0, []);
     
    // This code is contributed by mukesh07.
</script>

                    

Output
1 2 3 6 
1 2 5 6 
1 4 5 6 
1 4 5 2 3 6 

Complexity Analysis:

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


Similar Reads

Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths
Given a matrix mat[][] with N rows and M columns. The task is to find the minimum number of changes required in the matrix such that every path from top left to bottom right is a palindromic path. In a path only right and bottom movements are allowed from one cell to another cell.Examples: Input: mat[][] = {{1, 2}, {3, 1}} Output: 0 Explanation: Ev
18 min read
Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths | Set 2
Given a matrix mat[][] with N rows and M columns. The task is to find the minimum number of changes required in the matrix such that every path from top left to bottom right is a palindromic path. In a path only right and bottom movements are allowed from one cell to another cell. Examples: Input: M = 2, N = 2, mat[M][N] = {{0, 0}, {0, 1}} Output:
12 min read
Print all palindromic paths from top left to bottom right in a matrix
Given a matrix containing lower alphabetical characters only, we need to print all palindromic paths in given matrix. A path is defined as a sequence of cells starting from top-left cell and ending at bottom-right cell. We are allowed to move to right and down only from current cell. We cannot go down diagonally. Example: Input : mat[][] = {"aaab”,
7 min read
Print all possible paths from top left to bottom right in matrix
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
8 min read
Count of possible paths from top left to bottom right of a M x N matrix by moving right, down or diagonally
Given 2 integers M and N, the task is to find the count of all the possible paths from top left to the bottom right of an M x N matrix with the constraints that from each cell you can either move only to right or down or diagonally Examples: Input: M = 3, N = 3Output: 13Explanation: There are 13 paths as follows: VVHH, VHVH, HVVH, DVH, VDH, VHHV, H
14 min read
Minimum Cost Path with Left, Right, Bottom and Up moves allowed
Given a two-dimensional grid, each cell of which contains an integer cost which represents a cost to traverse through that cell, we need to find a path from the top left cell to the bottom right cell by which the total cost incurred is minimum. Note: It is assumed that negative cost cycles do not exist in input matrix. This problem is an extension
14 min read
Minimum steps to convert all top left to bottom right paths in Matrix as palindrome | Set 2
Given a matrix mat[][] with N rows and M columns. The task is to find the minimum number of changes required in the matrix such that every path from top left to bottom right is a palindromic path. In a path only right and bottom movements are allowed from one cell to another cell. Examples: Input: mat[][] = {{1, 2}, {3, 1}}Output: 0Explanation:Ever
9 min read
Minimize flips required to make all shortest paths from top-left to bottom-right of a binary matrix equal to S
Given a binary matrix mat[][] having dimensions N * M and a binary string S of length N + M - 1 , the task is to find the minimum number of flips required to make all shortest paths from the top-left cell to the bottom-right cell equal to the given string S. Examples: Input: mat[][] = [[1, 0, 1, 1], [1, 1, 1, 0]], S = "10010"Output: 3 Explanation:
6 min read
Count all possible paths from top left to bottom right of a Matrix without crossing the diagonal
Given an integer N which denotes the size of a matrix, the task is to find the number of possible ways to reach the bottom-right corner from the top-left corner of the matrix without crossing the diagonal of the matrix. The possible movements from any cell (i, j) from the matrix are (i, j + 1) (Right) or (i + 1, j) (Down). Examples: Input: N = 4Out
6 min read
Minimize count of unique paths from top left to bottom right of a Matrix by placing K 1s
Given two integers N and M where M and N denote a matrix of dimensions N * M consisting of 0's only. The task is to minimize the count of unique paths from the top left (0, 0) to bottom right (N - 1, M - 1) of the matrix across cells consisting of 0's only by placing exactly K 1s in the matrix. Note: Neither the bottom right nor the top-left cell c
10 min read