Count of all unique paths from given source to destination in a Matrix
Last Updated :
16 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:
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++
#include <bits/stdc++.h>
using namespace std;
int countPaths( int i, int j, int count,
int p, int q)
{
if (i == p || j == q) {
count++;
return count;
}
count = countPaths(i, j + 1,
count, p, q);
count = countPaths(i + 1, j,
count, p, q);
return count;
}
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;
}
|
Java
class GFG {
static int countPaths( int i, int j, int count,
int p, int q) {
if (i == p || j == q) {
count++;
return count;
}
count = countPaths(i, j + 1 ,
count, p, q);
count = countPaths(i + 1 , j,
count, p, q);
return count;
}
public static void main(String args[]) {
int [] s = { 0 , 0 };
int [] d = { 1 , 2 };
System.out.println(countPaths(s[ 0 ], s[ 1 ], 0 , d[ 0 ], d[ 1 ]));
}
}
|
Python3
def countPaths(i, j, count, p, q):
if (i = = p or j = = q):
count + = 1
return count
count = countPaths(i, j + 1 , count, p, q)
count = countPaths(i + 1 , j, count, p, q)
return count
if __name__ = = "__main__" :
mat = [[ 1 , 2 , 3 ],
[ 4 , 5 , 6 ]]
s = [ 0 , 0 ]
d = [ 1 , 2 ]
print (countPaths(s[ 0 ], s[ 1 ], 0 , d[ 0 ], d[ 1 ]))
|
C#
using System;
class GFG {
static int countPaths( int i, int j, int count, int p, int q) {
if (i == p || j == q) {
count++;
return count;
}
count = countPaths(i, j + 1,
count, p, q);
count = countPaths(i + 1, j,
count, p, q);
return count;
}
public static void Main() {
int [] s = { 0, 0 };
int [] d = { 1, 2 };
Console.Write(countPaths(s[0], s[1], 0, d[0], d[1]));
}
}
|
Javascript
<script>
function countPaths(i, j, count,
p, q)
{
if (i == p || j == q) {
count++;
return count;
}
count = countPaths(i, j + 1,
count, p, q);
count = countPaths(i + 1, j,
count, p, q);
return count;
}
let mat = [[1, 2, 3],
[4, 5, 6]];
let s = [0, 0];
let d = [1, 2];
document.write(countPaths(s[0], s[1], 0,
d[0], d[1]));
</script>
|
Time Complexity: O(n+m)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...