Count the number of ways to traverse a Matrix - GeeksforGeeks

03 Jun, 2021
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 the above approach:
C++
Java
Python3
C#
PHP
Javascript
// 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 codeint main(){    int n = 5;    int m = 5;    cout << countPaths(n, m);    return 0;}
// 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 Codepublic 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)
# Python3 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
// 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 Codepublic 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
<?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?>
<script>    // Javascript 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);    }         let n = 5, m = 5;    document.write(countPaths(n, m)); // This code is contributed by suresh07.</script>
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++
Java
Python3
C#
PHP
Javascript
// 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 codeint main(){    int n = 5;    int m = 5;    cout << countPaths(n, m);    return 0;}
// 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)
# 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 codeif __name__ =="__main__":         n = 5    m = 5    print(countPaths(n, m)) # This code is contributed# by ChitraNayal
// 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)
<?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?>
<script>    // 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)    {        let dp = new Array(m+1);        for (let i=0; i<=m; i++)        {            dp[i] = new Array(n + 1);            for (let j=0; j<=n; j++)            {                dp[i][j] = 0;            }        }                  for (let i=1; i<=m; i++)        {            for (let 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];    }         let n = 5;    let m = 5;    document.write(countPaths(n, m));     </script>
70
Time Complexity: O(m * n)
Another Method(Efficient):
There is one more efficient way of reaching the solution in O(m) or O(n) whichever is greater.
We can permute the number of right operations and down operations.
Explanation:
In the given figure, we can see that for a matrix of 3×3, we need 2 right operations and 2 down operations.
Thus, we can permute these operations in any order, still we can reach the bottom-right.
“RRDD”,”RDRD”,”RDDR”,”DRDR”,”DDRR”,”DRRD”
Let the number of columns be m, and the number of rows is n, then no of permutations = (m+n)!/ (m!*n!)
Below is the implementation of the above logic.
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include<bits/stdc++.h>using namespace std; // Find factorialint factorial(int n){    int res = 1, i;         for(i = 2; i <= n; i++)        res *= i;             return res;} // Find number of ways to reach// mat[m-1][n-1] from mat[0][0]// in a matrix mat[][]] int countWays(int m, int n){    m = m - 1;    n = n - 1;         return factorial(m + n) /          (factorial(m) *           factorial(n));} // Driver Codeint main(){    int m = 5;    int n = 5;        // Function call    int result = countWays(m, n);         cout << result;} // This code is contributed by chahattekwani71
// Java Program for above approachimport java.io.*; class GFG {     // Find factorial    static int factorial(int n)    {        int res = 1, i;        for (i = 2; i <= n; i++)            res *= i;        return res;    }    // Find number of ways to reach    // mat[m-1][n-1] from mat[0][0]    // in a matrix mat[][]]    static int countWays(int m, int n)    {        m = m - 1;        n = n - 1;        return factorial(m + n)            / (factorial(m) * factorial(n));    }     // Driver Code    public static void main(String[] args)    {        int m = 5;        int n = 5;               // Function Call        int result = countWays(m, n);        System.out.println(result);    }}
# Python3 program for# the above approach # Find factorialdef factorial(n):     res = 1         for i in range(2, n + 1):        res *= i             return res # Find number of ways to reach# mat[m-1][n-1] from mat[0][0]# in a matrix mat[][]]def countWays(m, n):     m = m - 1    n = n - 1       return (factorial(m + n) //           (factorial(m) *            factorial(n))) # Driver code  m = 5n = 5 # Function callresult = countWays(m, n) print(result) # This code is contributed by divyeshrabadiya07
// C# Program for above approachusing System; class GFG{     // Find factorialstatic int factorial(int n){    int res = 1, i;    for(i = 2; i <= n; i++)        res *= i;             return res;} // Find number of ways to reach// mat[m-1][n-1] from mat[0][0]// in a matrix mat[][]]static int countWays(int m, int n){    m = m - 1;    n = n - 1;         return factorial(m + n) /          (factorial(m) * factorial(n));} // Driver codestatic void Main(){    int m = 5;    int n = 5;        // Function Call    int result = countWays(m, n);         Console.WriteLine(result);}} // This code is contributed by divyesh072019
<script> // JavaScript Program for above approach      // Find factorialfunction factorial( n){    var res = 1, i;    for(i = 2; i <= n; i++)        res *= i;              return res;}  // Find number of ways to reach// mat[m-1][n-1] from mat[0][0]// in a matrix mat[][]]function countWays( m,  n){    m = m - 1;    n = n - 1;          return factorial(m + n) /          (factorial(m) * factorial(n));}  // Driver code     var m = 5;    var n = 5;         // Function Call    var result = countWays(m, n);          document.write(result);     </script>
70
Time Complexity: O(n)
SoumikMondal
ankthon
ukasp
jit_t
Akanksha_Rai
ihritik
Rajput-Ji
Shubham Agrawal 13
chahattekwani71
divyeshrabadiya07
divyesh072019
bunnyram19
suresh07
Technical Scripter 2018
Dynamic Programming
Matrix
Dynamic Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Subset Sum Problem | DP-25
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Sudoku | Backtracking-7