动态规划求解国际象棋中车点到点的最短路径总数

来源:互联网 发布:mac ssh目录在哪里 编辑:程序博客网 时间:2024/05/22 02:01

题目:国际象棋中的车可以水平或竖直移动。一个车从棋盘的一角(0,0)移动到另一角(n,n),有多少种最短路径。


分析:对于n*n的棋盘,从(0,0)移动到(n,n)的最短路径总数应该为C(2n, n), 因为必走2n步,其中n步向左,剩下为向右。


public class ShortestStepsInChess {// from (0,0) to (n,n)// count[i,j] = count[i-1,j] + count[i,j-1]public static int cal(int n) {int[][] count = new int[n + 1][n + 1];for (int i = 0; i <= n; i++) {count[0][i] = 1;// (0,0) walk to (0,i) use i steps, just 1 solutioncount[i][0] = 1;// (0,0) walk to (i,0) use i steps, just 1 solution}for (int i = 1; i <= n; i++)for (int j = 1; j <= n; j++) {count[i][j] = count[i - 1][j] + count[i][j - 1];assert count[i][j] == SetUtils.combination(i + j, i);}return count[n][n];}public static void main(String[] args) {System.out.println(cal(4));}}


0 0
原创粉丝点击