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] β†’ [1, 2]
  2. [1, 2] β†’ [1, 1]
  3. [1, 1] β†’ [1, 2]
  4. [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 input

Input : 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

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int numberOfWays(int R, int C, int k, vector<int>& s, vector<int>& d) {
// Your code goes here
}
};
Test Case

Input:

Dest
K
M
N
Source