Walking Blocks
December 04 2006 11:25 PM

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.

Comments (1), Add Comment
How about this solution? It can be defined by simple recursion: Walk(0,0) = 0 Walk(x,0) = 1 Walk(0,y) = 1 Walk(x,y) = Walk(x-1,y) + Walk(x,y-1) Of course, you can optimize this using memoization. I tested this out on your program and it seems to work.
on December 05 2006 09:06 AM