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

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)

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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
?>

chevron_right



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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 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 calculatest he 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 calculatest he 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

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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
    count = [[0 for x in range(m)] for y in range(n)]
    
    # 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(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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 calculatest he 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

chevron_right



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.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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));
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right



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)!.

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