The Wayback Machine - https://web.archive.org/web/20211211093118/https://www.geeksforgeeks.org/count-of-all-unique-paths-from-given-source-to-destination-in-a-matrix/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count of all unique paths from given source to destination in a Matrix

  • Last Updated : 10 Dec, 2021

Given a 2D matrix of size n*m, a source ‘s’ and a destination ‘d’, print the count of all unique paths from given ‘s’ to ‘d’.  From each cell, you can either move only to the right or down.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[][] = { {1, 2, 3}, {4, 5, 6} }, s = {0, 0}, d = {1, 2}
Output: 3
Explanation: All possible paths from source to destination are:



  • 1 -> 4 -> 5 -> 6
  • 1 -> 2 -> 5 -> 6
  • 1 -> 2 -> 3 -> 6

Input: arr[][] = { {1, 2}, {3, 4} }, s = {0, 1}, d = {1, 1}
Output: 1

 

Approach: Use recursion to move right first & then down from each cell in the path of the matrix, starting from the source. If the destination is reached, increment the count of possible paths.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the
// count of all possible paths
int countPaths(int i, int j, int count,
               int p, int q)
{
    // Destination is reached
    if (i == p || j == q) {
        count++;
        return count;
    }
  
    // Move right
    count = countPaths(i, j + 1,
                       count, p, q);
  
    // Move down
    count = countPaths(i + 1, j,
                       count, p, q);
    return count;
}
  
// Driver program to test above functions
int main()
{
    vector<vector<int> > mat = { { 1, 2, 3 },
                                 { 4, 5, 6 } };
    vector<int> s = { 0, 0 };
    vector<int> d = { 1, 2 };
    cout << countPaths(s[0], s[1], 0,
                       d[0], d[1]);
    return 0;
}
Output
3

Time Complexity: O(n+m)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up

Start Your Coding Journey Now!