The following program counts the number of south-easterly paths through a regular grid of city streets. Inputs are the number of streets between the start point and end points, inclusively. So, if the points are 2 blocks apart in either direction then my inputs are x=3 and y=3.
public class BlockWalk {
public static void main(String[] args) {
int width = Integer.parseInt(args[0]);
int height = Integer.parseInt(args[1]);
System.out.println("There are " + (new BlockWalk(width, height)).countPaths() + " paths through a " + width + "x" + height + " grid.");
}
private int width, height;
public BlockWalk(int width, int height) {
this.width = width;
this.height = height;
}
public int countPaths() {
return countPathsFrom(0, 0);
}
private int countPathsFrom(int x, int y) {
if (x == width - 1 && y == height - 1)
return 1;
else if (x == width - 1 && y < height - 1)
return countPathsFrom(x, y + 1);
else if (x < width - 1 && y == height - 1)
return countPathsFrom(x + 1, y);
else
return countPathsFrom(x + 1, y) + countPathsFrom(x, y + 1);
}
}
This isn't an optimal solution, but it works. To optimize it you could maintain a table of partial solutions. Because the solution is recursive you can see that the solution for a 4x4 grid involves computing the solutions for both a 3x4 and a 4x3 grid and adding them together. Now you know that the the number of paths through a 3x4 are the same as the number of paths through a 4x3 grid. So no sense in computing the values for both. Once you have one of the answers stick it in a table. And always check the table before computing an answer. Not sure if that made sense... maybe if I'm bored another night I'll update with a code sample.
