An island is in the form of a square matrix, and a person is standing inside the matrix. The person can move one step in any direction (right, left, top, down) in the matrix. Calculate the probability that the person is alive after walking n steps on the island, provided that the person dies on stepping outside the matrix.

For example,

Input: 2 × 2 matrix
The starting coordinates is (0, 0)
The total number of steps is 1
 
Output: The alive probability is 0.5
 
 
Input: 3 × 3 matrix
The starting coordinates is (1, 1)
The total number of steps is 1
 
Output: The alive probability is 1
 
 
Input: 3 × 3 matrix
The starting coordinates is (0, 0)
The total number of steps is 3
 
Output: The alive probability is 0.25

Practice this problem

The following solution assumes all steps carry equal probability, i.e., 1/4 or 0.25. It can easily be modified to handle unequal probabilities.

 
We can easily solve this problem with the help of dynamic programming. For given position (x, y) and remaining steps n, the main problem can easily be divided into subproblems:

Prob(x, y, n) = (Prob(x – 1, y, n – 1) + Prob(x + 1, y, n – 1) +
                 Prob(x, y – 1, n – 1) + Prob(x, y + 1, n – 1)) / 4

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The alive probability is 0.25

Java


Download  Run Code

Output:

The alive probability is 0.25

Python


Download  Run Code

Output:

The alive probability is 0.25

The time complexity of the proposed solution is O(N2) for an N × N matrix. The auxiliary space required by the program is O(N2).