Robot Moving

Problem 9.2 from CtCI:

A robot starting from the upper left corner of a 2D grid, it can move only to the right or to the bottom, how many possible ways are there for it to move to point (x,y)?

I implemented my own version:


public class RobotMoving {

public int ways(int x, int y){
int[][] ways = new int[x+1][y+1];
ways[0][0] = 0;
ways[0][1] = 1;
ways[1][0] = 1;
for(int i = 1; i <= x; i++){
ways[i][0] = 1;
}
for(int i = 1; i <= y; i++){
ways[0][i] = 1;
}
for(int i = 1; i <= x; i++){
for(int j = 1; j <= y; j++){
ways[i][j] = ways[i-1][j] + ways[i][j-1];
System.out.print(ways[i][j] + "\t");
}
System.out.println();
}
return ways[x][y];
}

public static void main(String...strings){
RobotMoving test = new RobotMoving();
System.out.println(test.ways(3, 4));
}
}

Advertisements