Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count all possible paths from top left to bottom right of a mXn matrix

  • Difficulty Level : Easy
  • Last Updated : 02 Nov, 2021

The problem is to count all the possible paths from top left to bottom right of a mXn matrix with the constraints that from each cell you can either move only to right or down
Examples : 
 

Input :  m = 2, n = 2;
Output : 2
There are two paths
(0, 0) -> (0, 1) -> (1, 1)
(0, 0) -> (1, 0) -> (1, 1)

Input :  m = 2, n = 3;
Output : 3
There are three paths
(0, 0) -> (0, 1) -> (0, 2) -> (1, 2)
(0, 0) -> (0, 1) -> (1, 1) -> (1, 2)
(0, 0) -> (1, 0) -> (1, 1) -> (1, 2)

 

Become a success story instead of just reading about them. Prepare for coding interviews at Amazon and other top product-based companies with our Amazon Test Series. Includes topic-wise practice questions on all important DSA topics along with 10 practice contests of 2 hours each. Designed by industry experts that will surely help you practice and sharpen your programming skills. Wait no more, start your preparation today!

We have discussed a solution to print all possible paths, counting all paths is easier. Let NumberOfPaths(m, n) be the count of paths to reach row number m and column number n in the matrix, NumberOfPaths(m, n) can be recursively written as following.
 

C++




// A C++  program to count all possible paths
// from top left to bottom right
  
#include <iostream>
using namespace std;
  
// Returns count of possible paths to reach cell at row
// number m and column number n from the topmost leftmost
// cell (cell at 1, 1)
int numberOfPaths(int m, int n)
{
    // If either given row number is first or given column
    // number is first
    if (m == 1 || n == 1)
        return 1;
  
    // If diagonal movements are allowed then the last
    // addition is required.
    return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1);
    // + numberOfPaths(m-1, n-1);
}
  
int main()
{
    cout << numberOfPaths(3, 3);
    return 0;
}


Java




// A Java program to count all possible paths
// from top left to bottom right
  
class GFG {
  
    // Returns count of possible paths to reach
    // cell at row number m and column number n
    // from the topmost leftmost cell (cell at 1, 1)
    static int numberOfPaths(int m, int n)
    {
        // If either given row number is first or
        // given column number is first
        if (m == 1 || n == 1)
            return 1;
  
        // If diagonal movements are allowed then
        // the last addition is required.
        return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1);
        // + numberOfPaths(m-1, n-1);
    }
  
    public static void main(String args[])
    {
        System.out.println(numberOfPaths(3, 3));
    }
}
  
// This code is contributed by Sumit Ghosh


Python




# Python program to count all possible paths 
# from top left to bottom right
  
# function to return count of possible paths
# to reach cell at row number m and column
# number n from the topmost leftmost
# cell (cell at 1, 1)
def numberOfPaths(m, n):
# If either given row number is first
# or given column number is first
    if(m == 1 or n == 1):
        return 1
  
# If diagonal movements are allowed
# then the last addition
# is required.
    return numberOfPaths(m-1, n) + numberOfPaths(m, n-1)
  
# Driver program to test above function 
m = 3
n = 3
print(numberOfPaths(m, n))
  
# This code is contributed by Aditi Sharma


C#




// A C# program to count all possible paths
// from top left to bottom right
  
using System;
  
public class GFG {
    // Returns count of possible paths to reach
    // cell at row number m and column number n
    // from the topmost leftmost cell (cell at 1, 1)
    static int numberOfPaths(int m, int n)
    {
        // If either given row number is first or
        // given column number is first
        if (m == 1 || n == 1)
            return 1;
  
        // If diagonal movements are allowed then
        // the last addition is required.
        return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1);
        // + numberOfPaths(m-1, n-1);
    }
  
    static public void Main()
    {
        Console.WriteLine(numberOfPaths(3, 3));
    }
}
  
// This code is contributed by ajit


PHP




<?php
  
// Returns count of possible paths 
// to reach cell at row number m 
// and column number n from the 
// topmost leftmost cell (cell at 1, 1)
function numberOfPaths($m, $n)
{
      
    // If either given row number
    // is first or given column 
    // number is first
    if ($m == 1 || $n == 1)
            return 1;
      
    // If diagonal movements 
    // are allowed then the last 
    // addition is required.
    return numberOfPaths($m - 1, $n) + 
           numberOfPaths($m, $n - 1);
}
  
// Driver Code
echo numberOfPaths(3, 3);
      
// This code is contributed by akt_mit
?>


Javascript




<script>
// A Javascript program to count all possible paths
// from top left to bottom right
      
    // Returns count of possible paths to reach
    // cell at row number m and column number n
    // from the topmost leftmost cell (cell at 1, 1)
    function numberOfPaths(m, n)
    {
      
        // If either given row number is first or
        // given column number is first
        if (m == 1 || n == 1)
            return 1;
          
        // If diagonal movements are allowed then
        // the last addition is required.
        return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1);
         
       // + numberOfPaths(m - 1, n - 1);
    }
      
    document.write(numberOfPaths(3, 3)+"<br>");
      
    // This code is contributed by rag2127
</script>


Output: 
 



6

The time complexity of above recursive solution is exponential. There are many overlapping subproblems. We can draw a recursion tree for numberOfPaths(3, 3) and see many overlapping subproblems. The recursion tree would be similar to Recursion tree for Longest Common Subsequence problem
So this problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array count[][] in bottom up manner using the above recursive formula.
 

C++




// A C++ program to count all possible paths
// from top left to bottom right
#include <iostream>
using namespace std;
  
// Returns count of possible paths to reach cell at
// row number m and column  number n from the topmost
// leftmost cell (cell at 1, 1)
int numberOfPaths(int m, int n)
{
    // Create a 2D table to store results of subproblems
    int count[m][n];
  
    // Count of paths to reach any cell in first column is 1
    for (int i = 0; i < m; i++)
        count[i][0] = 1;
  
    // Count of paths to reach any cell in first row is 1
    for (int j = 0; j < n; j++)
        count[0][j] = 1;
  
    // Calculate count of paths for other cells in
    // bottom-up manner using the recursive solution
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++)
  
            // By uncommenting the last part the code calculates the total
            // possible paths if the diagonal Movements are allowed
            count[i][j] = count[i - 1][j] + count[i][j - 1]; //+ count[i-1][j-1];
    }
    return count[m - 1][n - 1];
}
  
// Driver program to test above functions
int main()
{
    cout << numberOfPaths(3, 3);
    return 0;
}


Java




// A Java program to count all possible paths
// from top left to bottom right
class GFG {
    // Returns count of possible paths to reach
    // cell at row number m and column number n from
    // the topmost leftmost cell (cell at 1, 1)
    static int numberOfPaths(int m, int n)
    {
        // Create a 2D table to store results
        // of subproblems
        int count[][] = new int[m][n];
  
        // Count of paths to reach any cell in
        // first column is 1
        for (int i = 0; i < m; i++)
            count[i][0] = 1;
  
        // Count of paths to reach any cell in
        // first column is 1
        for (int j = 0; j < n; j++)
            count[0][j] = 1;
  
        // Calculate count of paths for other
        // cells in bottom-up manner using
        // the recursive solution
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++)
  
                // By uncommenting the last part the
                // code calculates the total possible paths
                // if the diagonal Movements are allowed
                count[i][j] = count[i - 1][j] + count[i][j - 1]; //+ count[i-1][j-1];
        }
        return count[m - 1][n - 1];
    }
  
    // Driver program to test above function
    public static void main(String args[])
    {
        System.out.println(numberOfPaths(3, 3));
    }
}
  
// This code is contributed by Sumit Ghosh


Python




# Python program to count all possible paths 
# from top left to bottom right
  
# Returns count of possible paths to reach cell 
# at row number m and column number n from the 
# topmost leftmost cell (cell at 1, 1)
def numberOfPaths(m, n):
    # Create a 2D table to store
    # results of subproblems
    # one-liner logic to take input for rows and columns
    # mat = [[int(input()) for x in range (C)] for y in range(R)]
      
    count = [[0 for x in range(n)] for y in range(m)]
    
    # Count of paths to reach any 
    # cell in first column is 1
    for i in range(m):
        count[i][0] = 1;
    
    # Count of paths to reach any 
    # cell in first column is 1
    for j in range(n):
        count[0][j] = 1;
    
    # Calculate count of paths for other
    # cells in bottom-up 
    # manner using the recursive solution
    for i in range(1, m):
        for j in range(1, n):             
            count[i][j] = count[i-1][j] + count[i][j-1]
    return count[m-1][n-1]
  
# Driver program to test above function 
m = 3
n = 3
print( numberOfPaths(m, n))
  
# This code is contributed by Aditi Sharma


C#




// A C#  program to count all possible paths
// from top left to bottom right
using System;
  
public class GFG {
  
    // Returns count of possible paths to reach
    // cell at row number m and column number n from
    // the topmost leftmost cell (cell at 1, 1)
    static int numberOfPaths(int m, int n)
    {
        // Create a 2D table to store results
        // of subproblems
        int[, ] count = new int[m, n];
  
        // Count of paths to reach any cell in
        // first column is 1
        for (int i = 0; i < m; i++)
            count[i, 0] = 1;
  
        // Count of paths to reach any cell in
        // first column is 1
        for (int j = 0; j < n; j++)
            count[0, j] = 1;
  
        // Calculate count of paths for other
        // cells in bottom-up manner using
        // the recursive solution
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++)
  
                // By uncommenting the last part the
                // code calculates the total possible paths
                // if the diagonal Movements are allowed
                count[i, j] = count[i - 1, j] + count[i, j - 1]; //+ count[i-1][j-1];
        }
        return count[m - 1, n - 1];
    }
  
    // Driver program to test above function
    static public void Main()
    {
        Console.WriteLine(numberOfPaths(3, 3));
    }
}
  
// This code is contributed by akt_mit


PHP




<?php
// A PHP program to count all possible
// paths from top left to bottom right
  
// Returns count of possible paths to 
// reach cell at row number m and column 
// number n from the topmost leftmost 
// cell (cell at 1, 1)
function numberOfPaths($m, $n)
{
    // Create a 2D table to store
    // results of subproblems
    $count = array();
  
    // Count of paths to reach any cell
    // in first column is 1
    for ($i = 0; $i < $m; $i++)
        $count[$i][0] = 1;
  
    // Count of paths to reach any cell
    // in first column is 1
    for ($j = 0; $j < $n; $j++)
        $count[0][$j] = 1;
  
    // Calculate count of paths for other 
    // cells in bottom-up manner using the
    // recursive solution
    for ($i = 1; $i < $m; $i++)
    {
        for ($j = 1; $j < $n; $j++)
  
            // By uncommenting the last part the 
            // code calculated the total possible
            // paths if the diagonal Movements are allowed
            $count[$i][$j] = $count[$i - 1][$j] + 
                             $count[$i][$j - 1]; //+ count[i-1][j-1];
    }
    return $count[$m - 1][$n - 1];
}
  
// Driver Code
echo numberOfPaths(3, 3);
  
// This code is contributed
// by Mukul Singh
?>


Javascript




<script>
  
// A javascript program to count all possible paths
// from top left to bottom right
  
// Returns count of possible paths to reach
// cell at row number m and column number n from
// the topmost leftmost cell (cell at 1, 1)
function numberOfPaths(m , n)
{
    // Create a 2D table to store results
    // of subproblems
    var count = Array(m).fill(0).map(x => Array(n).fill(0));
  
    // Count of paths to reach any cell in
    // first column is 1
    for (i = 0; i < m; i++)
        count[i][0] = 1;
  
    // Count of paths to reach any cell in
    // first column is 1
    for (j = 0; j < n; j++)
        count[0][j] = 1;
  
    // Calculate count of paths for other
    // cells in bottom-up manner using
    // the recursive solution
    for (i = 1; i < m; i++) {
        for (j = 1; j < n; j++)
  
            // By uncommenting the last part the
            // code calculates the total possible paths
            // if the diagonal Movements are allowed
              
            //+ count[i-1][j-1];
            count[i][j] = count[i - 1][j] + count[i][j - 1]; 
    }
    return count[m - 1][n - 1];
}
  
// Driver program to test above function
document.write(numberOfPaths(3, 3));
  
// This code is contributed by 29AjayKumar 
  
</script>


Output: 

6

Time complexity of the above dynamic programming solution is O(mn). 
The space complexity of the above solution is O(mn).
Space Optimization of DP solution. 
Above solution is more intuitive but we can also reduce the space by O(n); where n is column size. 
 

C++




#include <bits/stdc++.h>
  
using namespace std;
  
// Returns count of possible paths to reach
// cell at row number m and column number n from
// the topmost leftmost cell (cell at 1, 1)
int numberOfPaths(int m, int n)
{
    // Create a 1D array to store results of subproblems
    int dp[n] = { 1 };
    dp[0] = 1;
  
    for (int i = 0; i < m; i++) {
        for (int j = 1; j < n; j++) {
            dp[j] += dp[j - 1];
        }
    }
  
    return dp[n - 1];
}
  
// Driver code
int main()
{
    cout << numberOfPaths(3, 3);
}
  
// This code is contributed by mohit kumar 29


Java




class GFG {
    // Returns count of possible paths to reach
    // cell at row number m and column number n from
    // the topmost leftmost cell (cell at 1, 1)
    static int numberOfPaths(int m, int n)
    {
        // Create a 1D array to store results of subproblems
        int[] dp = new int[n];
        dp[0] = 1;
  
        for (int i = 0; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[j] += dp[j - 1];
            }
        }
  
        return dp[n - 1];
    }
  
    // Driver program to test above function
    public static void main(String args[])
    {
        System.out.println(numberOfPaths(3, 3));
    }
}


Python3




# Returns count of possible paths 
# to reach cell at row number m and 
# column number n from the topmost 
# leftmost cell (cell at 1, 1)
def numberOfPaths(p, q):
      
    # Create a 1D array to store 
    # results of subproblems
    dp = [1 for i in range(q)]
    for i in range(p - 1):
        for j in range(1, q):
            dp[j] += dp[j - 1]
    return dp[q - 1]
  
# Driver Code
print(numberOfPaths(3, 3))
  
# This code is contributed
# by Ankit Yadav


C#




using System;
  
class GFG {
    // Returns count of possible paths
    // to reach cell at row number m
    // and column number n from the
    // topmost leftmost cell (cell at 1, 1)
    static int numberOfPaths(int m, int n)
    {
        // Create a 1D array to store
        // results of subproblems
        int[] dp = new int[n];
        dp[0] = 1;
  
        for (int i = 0; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[j] += dp[j - 1];
            }
        }
  
        return dp[n - 1];
    }
  
    // Driver Code
    public static void Main()
    {
        Console.Write(numberOfPaths(3, 3));
    }
}
  
// This code is contributed
// by ChitraNayal


PHP




<?php
// Returns count of possible paths to 
// reach cell at row number m and 
// column number n from the topmost 
// leftmost cell (cell at 1, 1)
function numberOfPaths($m, $n)
{
    // Create a 1D array to store 
    // results of subproblems
    $dp = array();
    $dp[0] = 1;
  
    for ($i = 0; $i < $m; $i++)
    {
    for ($j = 1; $j < $n; $j++)
    {
        $dp[$j] += $dp[$j - 1];
    }
    }
  
    return $dp[$n - 1];
}
  
// Driver Code
echo numberOfPaths(3, 3);
  
// This code is contributed 
// by Akanksha Rai
?>


Javascript




<script>
  
// Returns count of possible paths to reach
// cell at row number m and column number n from
// the topmost leftmost cell (cell at 1, 1)
function numberOfPaths(m , n)
{
    // Create a 1D array to store results of subproblems
    dp = Array.from({length: n}, (_, i) => 0);
    dp[0] = 1;
  
    for (i = 0; i < m; i++) {
        for (j = 1; j < n; j++) {
            dp[j] += dp[j - 1];
        }
    }
  
    return dp[n - 1];
}
  
// Driver program to test above function
document.write(numberOfPaths(3, 3));
  
// This code contributed by Princi Singh 
  
</script>


Output: 
 

6

This code is contributed by Vivek Singh
Note the count can also be calculated using the formula (m-1 + n-1)!/(m-1)!(n-1)!. 
Another Approach:(Using combinatorics) In this approach We have to calculate m+n-2 C n-1 here which will be (m+n-2)! / (n-1)! (m-1)! 

Now, let us see how this formula is giving the correct answer (Reference 1) (Reference 2) read reference 1 and reference 2 for a better understanding

m = number of rows

n = number of columns



Total number of moves in which we have to move down to reach the last row = m – 1 (m rows, since we are starting from (1, 1) that is not included)

Total number of moves in which we have to move right to reach the last column = n – 1 (n column, since we are starting from (1, 1) that is not included)

Down moves = (m – 1)

Right moves = (n – 1)

Total moves = Down moves + Right Moves = (m – 1) + (n – 1) 

Now think moves as a string of ‘R’ and ‘D’ character where ‘R’ at any ith index will tell us to move ‘Right’ and ‘D’ will tell us to move ‘Down’

Now think of how many unique strings (moves) we can make where in total there should be (n – 1 + m – 1) characters and there should be (m – 1) ‘D’ character and (n – 1) ‘R’ character? 

Choosing positions of (n – 1) ‘R’ characters, results in automatic choosing of (m – 1) ‘D’ character positions 

Calculate nCr 
Number of ways to choose positions for (n – 1) ‘R’ character = Total positions C n – 1 = Total positions C m – 1 = (n – 1 + m – 1) != \frac {(n - 1 + m - 1)!} {(n - 1) ! (m - 1)!} 

Another way to think about this problem: Count the Number of ways to make an N digit Binary String (String with 0s and 1s only) with ‘X’ zeros and ‘Y’ ones (here we have replaced ‘R’ with ‘0’ or ‘1’ and ‘D’ with ‘1’ or ‘0’ respectively whichever suits you better) 
 

C++




// A C++ program to count all possible paths from
// top left to top bottom using combinatorics
  
#include <iostream>
using namespace std;
  
int numberOfPaths(int m, int n)
{
    // We have to calculate m+n-2 C n-1 here
    // which will be (m+n-2)! / (n-1)! (m-1)!
    int path = 1;
    for (int i = n; i < (m + n - 1); i++) {
        path *= i;
        path /= (i - n + 1);
    }
    return path;
}
  
// Driver code
int main()
{
    cout << numberOfPaths(3, 3);
    return 0;
}
  
// This code is suggested by Kartik Sapra


Java




// Java program to count all possible paths from
// top left to top bottom using combinatorics
class GFG {
  
    static int numberOfPaths(int m, int n)
    {
        // We have to calculate m+n-2 C n-1 here
        // which will be (m+n-2)! / (n-1)! (m-1)!
        int path = 1;
        for (int i = n; i < (m + n - 1); i++) {
            path *= i;
            path /= (i - n + 1);
        }
        return path;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        System.out.println(numberOfPaths(3, 3));
    }
}
  
// This code is contributed by Code_Mech.


Python3




# Python3 program to count all possible 
# paths from top left to top bottom 
# using combinatorics
def numberOfPaths(m, n) :
  
    # We have to calculate m + n-2 C n-1 here 
    # which will be (m + n-2)! / (n-1)! (m-1)! path = 1;
    for i in range(n, (m + n - 1)):
        path *= i;
        path //= (i - n + 1);
      
    return path;
  
# Driver code
print(numberOfPaths(3, 3));
  
# This code is contributed 
# by Akanksha Rai


C#




// C# program to count all possible paths from
// top left to top bottom using combinatorics
using System;
  
class GFG {
  
    static int numberOfPaths(int m, int n)
    {
        // We have to calculate m+n-2 C n-1 here
        // which will be (m+n-2)! / (n-1)! (m-1)!
        int path = 1;
        for (int i = n; i < (m + n - 1); i++) {
            path *= i;
            path /= (i - n + 1);
        }
        return path;
    }
  
    // Driver code
    public static void Main()
    {
        Console.WriteLine(numberOfPaths(3, 3));
    }
}
  
// This code is contributed by Code_Mech.


PHP




<?php
  
// PHP program to count all possible paths from 
// top left to top bottom using combinatorics
function numberOfPaths($m, $n
{
    // We have to calculate m+n-2 C n-1 here 
    // which will be (m+n-2)! / (n-1)! (m-1)! 
    $path = 1;
    for ($i = $n; $i < ($m + $n - 1); $i++)
    {
        $path *= $i;
        $path /= ($i - $n + 1);
    }
    return $path;
}
  
// Driver code
{
    echo(numberOfPaths(3, 3));
}
  
// This code is contributed by Code_Mech.


Javascript




<script>
  
// javascript program to count all possible paths from
// top left to top bottom using combinatorics   
function numberOfPaths(m , n)
    {
        // We have to calculate m+n-2 C n-1 here
        // which will be (m+n-2)! / (n-1)! (m-1)!
        var path = 1;
        for (i = n; i < (m + n - 1); i++) {
            path *= i;
            path = parseInt(path/(i - n + 1));
        }
        return path;
    }
  
// Driver code
document.write(numberOfPaths(3, 3));
  
// This code contributed by Princi Singh 
</script>


Output: 

6

This article is contributed by Hariprasad NG. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!