Problem
You are given two integers n
and m
which represent the size of a
1-indexed grid. You are also given an integer k
, a 1-indexed integer array source
and a 1-indexed integer array dest
, where source
and
dest
are in the form [x, y]
representing a cell on the given grid.
You can move through the grid in the following way:
- You can go from cell
[x1, y1]
to cell[x2, y2]
if eitherx1 == x2
ory1 == y2
. - Note that you can ’t move to the cell you are already in e.g.
x1 == x2
andy1 == y2
.
Return the number of ways you can reach dest
from source
by moving through the grid exactly k
times.
Since the answer may be very large, return it modulo 109 + 7
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
2 <= n, m <= 10^9
1 <= k <= 10^5
source.length == dest.length == 2
1 <= source[1], dest[1] <= n
1 <= source[2], dest[2] <= m
Solution
Method 1 – Dynamic Programming with State Compression
Intuition
Since the grid is huge, we can’t use a 2D DP. The only thing that matters is whether we are in the same row or same column as the destination. We can use a 2-state DP: at each step, track the number of ways to be in the same row as dest, and the number of ways to be in the same column as dest.
Approach
- Let dp_row = number of ways to be in the same row as dest after t steps, dp_col = number of ways to be in the same column as dest after t steps.
- At each step, you can move from row to col or col to row, except you can’t stay in the same cell.
- Use matrix exponentiation or iterative DP for k steps, updating dp_row and dp_col at each step.
- Initialize dp_row and dp_col based on whether source is in the same row or column as dest.
- Return the number of ways to reach dest in exactly k steps.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(k)
, where k is the number of steps. - 🧺 Space complexity:
O(1)
, only a few variables are used.