Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Count paths in a grid recursively

Count distinct paths from top-left to bottom-right moving only right or down using recursion with memoization.

Python practice9 minRecursion & BacktrackingBeginnerLast updated March 27, 2026

Problem statement

Given two positive integers rows and cols representing the number of rows and columns in a grid, count how many unique paths exist from the top-left corner to the bottom-right corner if you may only move right or down at each step. Implement the solution using recursion and memoization (to avoid exponential time).

Task

Practice recursive problem solving and memoization by counting grid paths.

Examples

2x2 grid

Input

rows=2, cols=2

Output

2

Two paths: right->down or down->right.

Input format

Two integers: rows and cols (both >= 1).

Output format

An integer: the number of distinct paths.

Constraints

1 <= rows, cols <= 20 (answers fit in a 64-bit integer for these ranges).

Samples

Sample 1

Input

rows=3, cols=3

Output

6

Paths count equals binomial coefficient C(4,2) = 6.