Random Walks in 2 Dimensions

There are a few variants of this problem:

1) A person does a random 2D walk. What is the probability that he gets to the bottom of a grid before any of the sides?

2) A person does a random 2D walk. What is the probability that he gets to a particular square at time n?

There are several methods of solving this problem, including:

i) Generating Pascal's Triangle in 2 Dimensions

ii) Iterating a Markov Process on the boundary/particular point

iii) Solving the linear system (if he has equal probability to walk each way) with conjugate gradient.

The fastest to code is the Markov Decision Process. It runs in O(n * k), where k is the number of iterations (usually 1000-10000) and n is the total number of grid squares. You set 1.0 as the starting value for the desired endpoints, 0.0 elsewhere, and iterate as follows. The final array at the X, Y coordinates that you are interested in give you the probability that a random walk starting at X,Y ends up at your chosen squares.

The following code solves the first problem, but can easily be extended to solve the second by changing the initial values.

Java - Markov Decision Process
static double arr[][] ; public static void main(String[] args) {        Scanner input = new Scanner(System.in) ; int W = input.nextInt ; // WIDTH int H = input.nextInt ; // HEIGHT int X = input.nextInt ; // STARTING X        int Y = input.nextInt ; // STARTING Y         while (W+H+X+Y != 0) {            // Total Width = W+1, Total Height = H+1 arr = new double[110][110] ; for (int i = 1 ; i &lt;= W ; i ++ ) {                arr[i][0] = 1.0 ; arr[i][H] = 0.0 ; }            // This program starts with 1.0 along the bottom boundary, 0.0 elsewhere. for (int i = 2 ; i &lt; W ; i ++) for (int j = 1 ; j &lt;= H ; j ++) arr[i][j] = 0.0 ; for (int k = 0 ; k &lt; 10000 ; k ++) for (int i = 1 ; i &lt;= W ; i ++ ) for (int j = 1 ; j &lt;= H ; j ++) {                        arr[i][j] = (arr[i+1][j] + arr[i-1][j] + arr[i][j+1] + arr[i][j-1]) / 4 ; // Change this statement if he doesn't have equal probability of walking in each direction }            // k is the number of steps, change k for WA/AC/TLE System.out.printf("%.3f",arr[X][Y]); W = input.nextInt ; H = input.nextInt ; X = input.nextInt ; Y = input.nextInt ; }    }