Count the number of ways to traverse a Matrix

Given a two-dimensional matrix, in how way can someone traverse it from top-left to bottom-right?
Condition- At any particular cell the possible moves are either down or right, no other steps possible.

Stop when the end is reached.



Examples:

Input : 3 3
Output : 6

Input : 5 5
Output : 70

If we look closely, we will find that the number of ways a cell can be reached is = Number of ways it can reach the cell above it + number of ways it can reach the cell which is left of it.
So, start filling the 2D array according to it and return the last cell after completely filling the array.

Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program using recursive solution to count
// number of ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
#include <bits/stdc++.h>
using namespace std;
  
// Returns The number of way from top-left 
// to mat[m-1][n-1]
int countPaths(int m, int n)
{
    // Return 1 if it is the first row or 
    // first column
    if (m == 1 || n == 1)
        return 1;
   
    // Recursively find the no of way to 
    // reach the last cell.
    return countPaths(m - 1, n) + 
           countPaths(m, n - 1);
}
  
// Driver code
int main()
{
    int n = 5;
    int m = 5; 
    cout << countPaths(n, m);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program using recursive 
// solution to count number of 
// ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
import java.lang.*;
import java.util.*;
  
class GFG
{
// Returns The number of way 
// from top-left to mat[m-1][n-1]
public int countPaths(int m, int n)
{
    // Return 1 if it is the first
    // row or first column
    if (m == 1 || n == 1)
        return 1;
  
    // Recursively find the no of 
    // way to reach the last cell.
    return countPaths(m - 1, n) +
           countPaths(m, n - 1);
}
  
// Driver Code
public static void main(String args[])
{
    GFG g = new GFG();
  
    int n = 5, m = 5;
    System.out.println(g.countPaths(n, m));
}
}
  
// This code is contributed 
// by Akanksha Rai(Abby_akku) 

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program using recursive solution to count 
# number of ways to reach mat[m-1][n-1] from 
# mat[0][0] in a matrix mat[][]
  
# Returns The number of way from top-left 
# to mat[m-1][n-1] 
def countPaths(m, n) :
  
    # Return 1 if it is the first row or 
    # first column 
    if m == 1 or n == 1 :
        return 1
  
    # Recursively find the no of way to 
    # reach the last cell. 
    return (countPaths(m - 1, n) + 
            countPaths(m, n - 1))
  
  
# Driver code     
if __name__ == "__main__" :
  
    n = 5
    m = 5
    print(countPaths(n, m))
  
# This code is contributed by ANKITRAI1

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program using recursive 
// solution to count number of 
// ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
using System;
  
class GFG
{
// Returns The number of way 
// from top-left to mat[m-1][n-1]
public int countPaths(int m, int n)
{
    // Return 1 if it is the first
    // row or first column
    if (m == 1 || n == 1)
        return 1;
  
    // Recursively find the no of 
    // way to reach the last cell.
    return countPaths(m - 1, n) +
        countPaths(m, n - 1);
}
  
// Driver Code
public static void Main()
{
    GFG g = new GFG();
  
    int n = 5, m = 5;
    Console.WriteLine(g.countPaths(n, m));
    Console.Read();
}
}
  
// This code is contributed 
// by SoumikMondal 

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program using recursive 
// solution to count number of 
// ways to reach mat[m-1][n-1] from 
// mat[0][0] in a matrix mat[][] 
  
// Returns The number of way 
// from top-left to mat[m-1][n-1] 
  
function countPaths($m, $n
    // Return 1 if it is the 
    // first row or first column 
    if ($m == 1 || $n == 1) 
        return 1; 
  
    // Recursively find the no of 
    // way to reach the last cell. 
    return countPaths($m - 1, $n) + 
           countPaths($m, $n - 1); 
  
// Driver code 
$n = 5; 
$m = 5; 
echo countPaths($n, $m); 
  
// This code is contributed by jit_t
?>

chevron_right


Output:

70

The above solution has exponential time complexity. It can be optimized using Dynamic Programming as there are overlapping subproblems (highlighted below in partial recursion tree for m=3, n=3)

            CP(3, 3)
          /        \
     CP(2, 3)     CP(3, 2)
     /    \        /     \
 CP(1,3) CP(2,2) CP(2,2) CP(3,1)

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple recursive solution to count
// number of ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
#include <bits/stdc++.h>
using namespace std;
  
// Returns The number of way from top-left 
// to mat[m-1][n-1]
int countPaths(int m, int n)
{
    int dp[m+1][n+1];
      
    for (int i=1; i<=m; i++)
    {
        for (int j=1; j<=n; j++)
        {
           if (i==1 || j == 1)
              dp[i][j] = 1;
            else
              dp[i][j] = dp[i-1][j] + dp[i][j-1];              
        }
    }
    
    return dp[m][n];
}
  
// Driver code
int main()
{
    int n = 5;
    int m = 5; 
    cout << countPaths(n, m);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple recursive solution to count
// number of ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
  
class GFG
{
    // Returns The number of way from top-left 
    // to mat[m-1][n-1]
    static int countPaths(int m, int n)
    {
        int [][]dp=new int[m+1][n+1];
          
        for (int i=1; i<=m; i++)
        {
            for (int j=1; j<=n; j++)
            {
            if (i==1 || j == 1)
                dp[i][j] = 1;
                else
                dp[i][j] = dp[i-1][j] + dp[i][j-1];             
            }
        }
      
        return dp[m][n];
    }
      
    // Driver code
    public static void main(String []args)
    {
        int n = 5;
        int m = 5
        System.out.println(countPaths(n, m));
          
    }
}
  
// This code is contributed 
// by ihritik (Hritik Raj)

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# A simple recursive solution to 
# count number of ways to reach 
# mat[m-1][n-1] from mat[0][0] 
# in a matrix mat[][]
  
# Returns The number of way 
# from top-left to mat[m-1][n-1]
def countPaths(m, n):
  
    dp = [[0 for i in range(m + 1)] 
             for j in range(n + 1)]
      
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if (i == 1 or j == 1):
                dp[i][j] = 1
            else:
                dp[i][j] = (dp[i - 1][j] + 
                            dp[i][j - 1])             
      
    return dp[m][n]
  
# Driver code
if __name__ =="__main__":
      
    n = 5
    m = 5
    print(countPaths(n, m))
  
# This code is contributed 
# by ChitraNayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple recursive solution to count
// number of ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
  
using System;
class GFG
{
    // Returns The number of way from top-left 
    // to mat[m-1][n-1]
    static int countPaths(int m, int n)
    {
        int [,]dp=new int[m+1,n+1];
          
        for (int i=1; i<=m; i++)
        {
            for (int j=1; j<=n; j++)
            {
            if (i==1 || j == 1)
                dp[i,j] = 1;
                else
                dp[i,j] = dp[i-1,j] + dp[i,j-1];             
            }
        }
      
        return dp[m,n];
    }
      
    // Driver code
    public static void Main()
    {
        int n = 5;
        int m = 5; 
        Console.WriteLine(countPaths(n, m));
          
    }
}
  
// This code is contributed 
// by ihritik (Hritik Raj)

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// A simple recursive solution to count
// number of ways to reach mat[m-1][n-1] 
// from mat[0][0] in a matrix mat[][]
  
// Returns The number of way from top-left 
// to mat[m-1][n-1]
function countPaths($m, $n)
{
    $dp;
      
    for ($i = 1; $i <= $m; $i++)
    {
        for ($j = 1; $j <= $n; $j++)
        {
            if ($i == 1 || $j == 1)
                $dp[$i][$j] = 1;
            else
                $dp[$i][$j] = $dp[$i - 1][$j] + 
                              $dp[$i][$j - 1];             
        }
    }
  
    return $dp[$m][$n];
}
  
// Driver code
$n = 5;
$m = 5; 
echo countPaths($n, $m);
  
// This code is contributed by Rajput-Ji
?>

chevron_right


Output:

70

Time Complexity : O(m * n)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.