/**
 * Compute the number of paths from (1,1) to (n,n).  N is given on
 * the command line.  Is not very friendly about errors.  Uses
 * a two-dimensional array to keep track of previously computed
 * values.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of October 1999
 */
public class IterativeNumPaths {

  /** Are we testing? */
  protected boolean testing = false;

  /**
   * Compute the number of paths from (row,col) to (n,n).
   * (row,col) should not be (n,n).
   */
  public int numPaths(int row, int col, int n)
  {
  
    // A two dimensional array to keep track of the number of paths
    // from (x,y) to (n,n).  pathsFrom[x-1][y-1] gives the number
    // of paths from (x,y) to (n,n).
    int[][] pathsFrom = new int[n][n];
    // We can fill in the last row and column.  There is only
    // one path from (x,n) or (n,y) to (n,n) .
    for (int i = 0; i < n; ++i) {
      pathsFrom[i][n-1] = 1;
      pathsFrom[n-1][i] = 1;
    }
    // Move backwards, a row at a time, filling in the distances.
    for (int x = n-2; x >= 0; x--)
      for (int y = n-2; y >= 0; y--)
        pathsFrom[x][y] = pathsFrom[x+1][y] + pathsFrom[x][y+1];
    // Testing: Print out the array
    if (testing) {
      SimpleOutput out = new SimpleOutput();
      for (int x = 1; x <= n; ++x) {
        for (int y = 1; y <= n; ++y) {
          out.print(pathsFrom[x-1][y-1] + " ");
        }
        out.println();
      }
    } // if testing
    // That's it, we're done.
    return pathsFrom[row-1][col-1];
  } // numPaths(int, int, int)

  public static void main(String[] args) {
    SimpleOutput out = new SimpleOutput();
    int n = Integer.parseInt(args[0]);
    IterativeNumPaths helper = new IterativeNumPaths();
    int count = helper.numPaths(1,1,n);
    out.println("There are " + count + " paths to (" + n + "," + n + ")");
  } // main(String[])
} // IterativeNumPaths

