给定水平和垂直道路的NxN网格。任务是找出人可以使用最短路径从点A到达点B的方式。
注意: A和B点是固定的,即A在左上角,B在右下角,如下图所示。
在上图中,以红色和浅绿色显示的路径是从点A到达点B的两条可能路径。
例子:
Input: N = 3
Output: Ways = 20
Input: N = 4
Output: Ways = 70
公式:
令网格为N x N,可以将多种方式写为。
以上公式如何运作?
让我们考虑如上所示的5×5网格的示例。为了在5×5网格中从点A到达点B,我们必须采取5个水平步长和5个垂直步长。每条路径将是10个步骤的排列,其中5个步骤是一种相同,其他5个步骤是第二种相同。所以
方式数= 10! /(5!* 5!),即252种方式。
C++
// C++ implementation of above approach
#include
using namespace std;
// function that will
// calculate the factorial
long factorial(int N)
{
int result = 1;
while (N > 0) {
result = result * N;
N--;
}
return result;
}
long countWays(int N)
{
long total = factorial(N + N);
long total1 = factorial(N);
return (total / total1) / total1;
}
// Driver code
int main()
{
int N = 5;
cout << "Ways = " << countWays(N);
return 0;
}
Java
// Java implementation of above approach
class GfG {
// function that will
// calculate the factorial
static long factorial(int N)
{
int result = 1;
while (N > 0) {
result = result * N;
N--;
}
return result;
}
static long countWays(int N)
{
long total = factorial(N + N);
long total1 = factorial(N);
return (total / total1) / total1;
}
// Driver code
public static void main(String[] args)
{
int N = 5;
System.out.println("Ways = " + countWays(N));
}
}
Python3
# Python3 implementation of above approach
# function that will calculate the factorial
def factorial(N) :
result = 1;
while (N > 0) :
result = result * N;
N -= 1;
return result;
def countWays(N) :
total = factorial(N + N);
total1 = factorial(N);
return (total // total1) // total1;
# Driver code
if __name__ == "__main__" :
N = 5;
print("Ways =", countWays(N));
# This code is contributed by Ryuga
C#
// C# implementation of above approach
using System;
class GfG
{
// function that will
// calculate the factorial
static long factorial(int N)
{
int result = 1;
while (N > 0)
{
result = result * N;
N--;
}
return result;
}
static long countWays(int N)
{
long total = factorial(N + N);
long total1 = factorial(N);
return (total / total1) / total1;
}
// Driver code
public static void Main(String []args)
{
int N = 5;
Console.WriteLine("Ways = " + countWays(N));
}
}
// This code is contributed by Arnab Kundu
PHP
0)
{
$result = $result * $N;
$N--;
}
return $result;
}
function countWays($N)
{
$total = factorial($N + $N);
$total1 = factorial($N);
return ($total / $total1) / $total1;
}
// Driver code
$N = 5;
echo "Ways = ", countWays($N);
// This code is contributed by ajit
?>
Javascript
输出:
Ways = 252