Given an n×n grid and three integers x, y, and k, a geek starts at cell [x, y]. At each move, the geek independently chooses one of the four directions - up, down, left, or right - with equal probability and moves one cell in that direction. If the geek moves outside the grid, it dies immediately.
Find the probability that the geek remains alive after exactly k moves.
Return the result as p × q-1 mod (109 + 7), where the probability is expressed as p / q and q-1 denotes the modular multiplicative inverse of q modulo 109 + 7.
Examples:
Input: n = 2, x = 1, y = 1, k = 1 Output: 500000004 Explanation: From (1, 1) on a 2×2 grid, only 2 out of 4 moves stay inside - left to (1, 0) and up to (0, 1). Probability = 2/4 = 1/2, and modular inverse of 2 mod 10^9+7 is 500000004.
[Naive Approach] Using Recursion – O(4^k) Time and O(k) Space
At each step, the person can move in one of 4 directions, each with probability 1/4. We recursively explore all possible paths of k steps and sum up the probabilities of paths that stay within the island.
If the current position is outside the island, return 0 (geek is dead).
If k == 0, return 1 (geek is alive at this position).
For each of the 4 directions, recursively compute the probability and multiply by 1/4, then sum all 4 results.
Output
500000004
[Expected Approach] Using Tabulation with Rolling Array – O(n^2 * k) Time and O(n^2) Space
In the recursive approach, the same (i, j, step) states are recomputed multiple times leading to exponential time. Instead of fixing this with memoization which still uses O(n^2*k) space for the dp table, we observe that to compute probabilities at step s+1 we only ever need the probabilities at step s - never any earlier step. So we use two rolling arrays curr and nxt, computing forward from step 0 to k, reducing space from O(n^2*k) to O(n^2).
Initialize curr[x][y] = 1 and all other cells to 0 - geek starts at (x, y) with probability 1.
For each step, create nxt as all zeros. For each cell (i, j) in curr, distribute curr[i][j] * (1/4) to each valid neighbor in nxt.
After each step, set curr = nxt discarding the old layer.