Ways in a Grid from One Point to Another (original) (raw)
Last Updated : 2 Apr, 2026
Given an N × N grid of horizontal and vertical roads, determine the number of ways to go from point A (top-left corner) to point B (bottom-right corner) using the shortest possible path.

**Input: N = 3
**Output: Ways = 20**Input: N = 4
**Output: Ways = 70
Iterative Combination Approach - O(N) Time and O(1) Space
From the top-left to bottom-right, you must take exactly N right moves and N down moves, making a total of 2N steps. Each path is an arrangement of these moves, so the problem reduces to choosing positions for one type of move among 2N positions. Hence, the number of ways is C(2N, N), computed efficiently using an iterative method.
Using the combination formula:
C(n, r) = \frac{n!}{r!(n - r)!}
We get,
C(2N, N) = \frac{(2N)!}{N! \cdot N!}
Expand the factorial:
(2N)! = (2N)(2N-1)(2N-2)...(N+1) \cdot N!
C(2N, N) = \frac{(2N)(2N−1)(2N−2)…(N+1) \cdot N!}{N! \cdot N!}
Instead of computing factorials (which is costly), we compute:
\binom{2N}{N} = \frac{(N+1)(N+2)\cdots(2N)}{1 \cdot 2 \cdots N}
For N = 5 the approach is:
- Initialize res = 1
- i = 1, res = 1 * (5 + 1) / 1 = 6
- i = 2, res = 6 * (5 + 2) / 2 = 21
- i = 3, res = 21 * (5 + 3) / 3 = 56
- i = 4, res = 56 × (5 + 4) / 4 = 126
- i = 5, res = 126 * (5 + 5) / 5 = 252
Final Answer = 252
C++ `
#include using namespace std;
int countWays(int N) { int res = 1;
// Compute C(2N, N)
for (int i = 1; i <= N; i++) {
res = res * (N + i) / i;
}
return res;}
int main() { int N = 5; cout << "Ways = " << countWays(N); return 0; }
Java
class GfG {
static long countWays(int N) {
long res = 1;
// Compute C(2N, N)
for (int i = 1; i <= N; i++) {
res = res * (N + i) / i;
}
return res;
}
public static void main(String[] args) {
int N = 5;
System.out.println("Ways = " + countWays(N));
}}
Python
def countWays(N): res = 1
# Compute C(2N, N)
for i in range(1, N + 1):
res = res * (N + i) // i
return resif name == "main": N = 5 print("Ways =", countWays(N))
C#
using System;
class GfG { static long countWays(int N) { long res = 1;
// Compute C(2N, N)
for (int i = 1; i <= N; i++)
{
res = res * (N + i) / i;
}
return res;
}
public static void Main(string[] args)
{
int N = 5;
Console.WriteLine("Ways = " + countWays(N));
}}
JavaScript
// Compute C(2N, N) using iterative method function countWays(N) { let res = 1;
// Compute C(2N, N)
for (let i = 1; i <= N; i++) {
res = res * (N + i) / i;
}
return res;}
// Driver code let N = 5; console.log("Ways = " + countWays(N));
`