矩阵中从给定源到目的地的所有唯一路径的计数
给定一个大小为n*m的二维矩阵,一个源“ s ”和一个目标“ d ”,打印从给定“ s ”到“ d ”的所有唯一路径的计数。从每个单元格中,您只能向右或向下移动。
例子:
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
方法:使用递归从矩阵路径中的每个单元格开始向右移动,然后向下移动,从源开始。如果到达目的地,则增加可能路径的计数。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
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 > mat = { { 1, 2, 3 },
{ 4, 5, 6 } };
vector s = { 0, 0 };
vector d = { 1, 2 };
cout << countPaths(s[0], s[1], 0,
d[0], d[1]);
return 0;
}
Java
// Java program for the above approach
class GFG {
// Function to find the
// count of all possible paths
static 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
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]));
}
}
// This code is contributed by gfgking.
Python3
# python program for the above approach
# Function to find the
# count of all possible paths
def countPaths(i, j, count, p, q):
# Destination is reached
if (i == p or j == q):
count += 1
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
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]))
# This code is contributed by rakeshsahni
C#
// C# program for the above approach
using System;
class GFG {
// Function to find the
// count of all possible paths
static 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
public static void Main() {
int[] s = { 0, 0 };
int[] d = { 1, 2 };
Console.Write(countPaths(s[0], s[1], 0, d[0], d[1]));
}
}
// This code is contributed by gfgking.
Javascript
输出
3
时间复杂度:O(n+m)
辅助空间:O(1)