667. Number of Ways to Reach Destination in the Grid
You are given two integers n and m which represent the size of a 1-indexed grid. You are also provided with 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 [xβ, yβ] to cell [xβ, yβ] if either xβ == xβ or yβ == yβ.
- Note that you can't move to the cell you are already in (i.e. you cannot have xβ == xβ and yβ == yβ).
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 10βΉ + 7.
Example 1:
Input : n = 2,Β m = 2,Β k = 4,Β source = [1, 1],Β dest = [2, 2]
Output : 8
Explanation :
ο»Ώ In total, there are 8 distinct sequences that achieve the goal. For instance, the valid sequences include:
- [1, 1] β [1, 2] β [1, 1] β [1, 2] β [2, 2]
- [1, 1] β [1, 2] β [1, 1] β [2, 1] β [2, 2]
- [1, 1] β [1, 2] β [2, 2] β [1, 2] β [2, 2]
- [1, 1] β [1, 2] β [2, 2] β [2, 1] β [2, 2]
- [1, 1] β [2, 1] β [1, 1] β [1, 2] β [2, 2]
- [1, 1] β [2, 1] β [1, 1] β [2, 1] β [2, 2]
- [1, 1] β [2, 1] β [2, 2] β [1, 2] β [2, 2]
- [1, 1] β [2, 1] β [2, 2] β [2, 1] β [2, 2]
Example 2:
Input : n = 2,Β m = 3,Β k = 4,Β source = [1, 1],Β dest = [1, 3]
Output : 11
Explanation :
One valid sequence from source [1, 1] to dest [1, 3] is:
- [1, 1] β [1, 2]
- [1, 2] β [1, 1]
- [1, 1] β [1, 2]
- [1, 2] β [1, 3]
There are 11 distinct sequences in total that allow reaching [1, 3] from [1, 1] in exactly 4 moves.
Now Your Turn!
Pick the correct output for the given inputInput : n = 3,Β m = 3,Β k = 4,Β source = [2, 1],Β dest = [2, 3]
Still unsure what the problem is asking ?
Letβs go through a few more examples, step by step, to make it clearer.
Constraints:
- 2 β€ n, m β€ 10βΉ
- 1 β€ k β€ 10β΅
- source.length == dest.length == 2
- 1 β€ source[1], dest[1] β€ n
- 1 β€ source[2], dest[2] β€ m