欧拉项目第15题 Lattice paths

来源:互联网 发布:第三次农业普查数据 编辑:程序博客网 时间:2024/06/06 09:16

Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.

How many such routes are there through a 20×20 grid?

从左上开始,只允许往右和往下走,20*20的格子到右下角有多少中走法。


思路如下,将格子看成二维数组,如2*2格子,x[3][3],从x[0][0] 走到x[3][3],每次x[i][j],i加1或者j加1。

容易得出x[0][j]、x[i][0] = 1, x[i][j] = x[i-1][j] + x[i][j-1],  x[i][j] = x[j][i]。

public static void main(String... args) {       Long[][] xx = new Long[21][21];       for(int i=0;i<21;i++){           for(int j=i;j < 21;j++) {               if(i == 0 || j==0) {                   xx[i][j] = 1l;                   xx[j][i] = xx[i][j];                   continue;               } else if(xx[j][i] != null) {                   xx[i][j] = xx[j][i];               } else {                   xx[i][j] = xx[i-1][j] + xx[i][j-1];                   xx[j][i] = xx[i][j];               }           }       }       System.out.println(xx[20][20]);    }

用integer中间会出现溢出,运行错误好几次,差点怀疑自己的思路。。。

0 0
原创粉丝点击