Problem Description
Given an n x m grid (indexed from 1) and two cells – source and dest – count the number of valid sequences of exactly k moves that take you from source to dest. In one move you may jump from a cell to any cell in the same row or the same column (but not remain in the same cell), and every intermediate cell must lie inside the grid. Since the answer can be huge, return it modulo 10^9+7.
Key Insights
- The grid movement splits naturally into independent vertical (row) and horizontal (column) moves.
- In each move you choose either to change rows or to change columns. In total, if you make r vertical moves and c horizontal moves (with r+c=k), then the vertical part must result in a net change equal to dest_row − source_row and similarly for the horizontal part.
- Because from any cell you can jump to any other cell in that row/column, the transitions for rows (and similarly for columns) form a complete directed “graph” (without self loops) of size n (or m). The number of ways to go from one fixed vertex to another in t moves in such a graph can be computed in closed form using eigen‐decomposition.
- The closed‐form formulas are:
For a graph of size N, the number of t‑move walks from vertex a to b is:
• If a == b: ( (N‑1)^t + (N‑1)⋅(–1)^t ) / N
• If a != b: ( (N‑1)^t − (–1)^t ) / N - The overall answer is then summing over all splits of k moves into vertical and horizontal parts, with an extra combinatorial factor (the number of ways to interleave these moves).
Space and Time Complexity
Time Complexity: O(k) – mainly due to summing over the possible split of k moves, and precomputing factorials/inverses for binomial coefficients. Space Complexity: O(k) – for storing factorials and inverse factorials up to k.
Solution
We first note that a valid path consists of a mix of vertical moves (affecting the row coordinate) and horizontal moves (affecting the column coordinate). Let r be the number of vertical moves and c = k − r be the number of horizontal moves. For each such split, the ways to perform vertical moves from source_row to dest_row can be computed using the formula for complete graphs:
• If source_row == dest_row: vertical_ways = ( (n−1)^r + (n−1)⋅(–1)^r ) / n
• If source_row != dest_row: vertical_ways = ( (n−1)^r − (–1)^r ) / n
A similar expression holds for horizontal moves (using m and the source/dest column values).
Since the order in which the vertical and horizontal moves occur matters, we multiply the product of the two counts by C(k, r) (i.e. “k choose r”) for interleaving.
The final answer is the sum over all valid splits of the product: answer = Σ[r=0 to k] ( C(k, r) * vertical_ways(r) * horizontal_ways(k − r) ) mod (10^9+7)
To handle large k, we precompute factorials and inverse factorials modulo (10^9+7) to calculate binomial coefficients efficiently. Exponentiations and modulo inversions are computed using fast modular exponentiation.