Number of Ways to Reach Destination in the Grid - Problem
Imagine you're navigating a grid-based board game where you can only move in straight lines! You start at a source position and need to reach a destination in exactly k moves.
The Challenge: Given an n ร m grid (1-indexed), a starting position source [x, y], and a destination dest [x, y], find the number of ways to reach the destination in exactly k steps.
Movement Rules:
- You can move from cell
[x1, y1]to[x2, y2]if eitherx1 == x2(same row) ory1 == y2(same column) - You cannot stay in the same cell (no self-loops)
- Each move counts as exactly 1 step
Goal: Return the total number of distinct paths of length k from source to destination, modulo 109 + 7.
Input & Output
example_1.py โ Basic Grid Navigation
$
Input:
n = 2, m = 3, k = 3, source = [1, 1], dest = [2, 3]
โบ
Output:
4
๐ก Note:
There are 4 different ways to reach destination [2,3] from source [1,1] in exactly 3 steps. Some example paths: [1,1] โ [1,2] โ [2,2] โ [2,3], [1,1] โ [1,3] โ [2,3] โ [2,1] โ [2,3], etc.
example_2.py โ Same Position
$
Input:
n = 3, m = 3, k = 2, source = [1, 1], dest = [1, 1]
โบ
Output:
16
๐ก Note:
To return to the same position in exactly 2 steps, we can move to any of the 4 adjacent cells (2 in same row + 2 in same column), then return. Each of the 4 first moves has 4 possible return moves, giving 4ร4 = 16 total paths.
example_3.py โ Impossible Case
$
Input:
n = 2, m = 2, k = 1, source = [1, 1], dest = [2, 2]
โบ
Output:
0
๐ก Note:
From [1,1], we can only move to [1,2] or [2,1] in one step (same row or column). We cannot reach [2,2] directly in 1 step since it requires changing both row and column.
Constraints
- 1 โค n, m โค 1000
- 0 โค k โค 1000
- 1 โค source[0], dest[0] โค n
- 1 โค source[1], dest[1] โค m
- Grid coordinates are 1-indexed
Visualization
Tap to expand
Understanding the Visualization
1
Valid Moves
From any position, rook can move to any cell in same row or column
2
Path Counting
Each sequence of k moves represents a unique path
3
Memoization
Cache results for (position, remaining_steps) to avoid recomputation
4
Final Count
Sum all valid k-step paths from source to destination
Key Takeaway
๐ฏ Key Insight: Transform the grid navigation into a state transition problem where each (position, steps_remaining) represents a unique subproblem that can be memoized for optimal efficiency.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code