Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. /**
  2.  * PascalTriangleArray is 2D array that store the value of Pascal Triangle.
  3.  * Later, can get the value of routes in grid nxn from PascalTriangleArray[n][n]
  4.  * Reference(s): http://blog.functionalfun.net/2008/07/project-euler-problem-15-city-grids-and.html
  5.  *
  6.  * @author MUHAMMAD AZRI BIN JASNI @ ABDUL RANI
  7.  * @version 04 NOVEMBER 2012
  8.  */
  9. public class solution15
  10. {
  11.     public static void main(String [] args)
  12.     {
  13.         long begin = System.currentTimeMillis();
  14.         int n = 20;
  15.         final int gridSize = n+1;
  16.         long PascalTriangleArray [][];
  17.         PascalTriangleArray = new long[gridSize][gridSize];
  18.         //i for row, j for column
  19.        
  20.         //set all column 0 to value 1.
  21.         for (int i=0; i<gridSize; i++)
  22.             PascalTriangleArray[i][0] = 1;
  23.            
  24.         //set all row 0 to value 1.
  25.         for (int j=0; j<gridSize; j++)
  26.             PascalTriangleArray[0][j] = 1;        
  27.        
  28.         //build the rest of PascalTriangleArray
  29.         for (int i=1; i<gridSize; i++)
  30.         {
  31.             for (int j=1; j<gridSize; j++)
  32.             {
  33.                 PascalTriangleArray[i][j] = PascalTriangleArray[i][j-1] + PascalTriangleArray[i-1][j] ;
  34.             }
  35.         }
  36.        
  37.         //display em
  38.         for (int i=0; i<gridSize; i++)
  39.         {
  40.             for (int j=0; j<gridSize; j++)
  41.             {
  42.                 System.out.print(PascalTriangleArray[i][j]+ " ");
  43.             }
  44.             System.out.println();
  45.         }
  46.        
  47.         System.out.println(n+"x"+n+" grid - no of routes: "+PascalTriangleArray[n][n]);
  48.         long end = System.currentTimeMillis();
  49.         System.out.println("Time: "+(end-begin) + "ms");
  50.     }
  51. }