您的位置:首页 > 其它

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

2014-05-15 17:49 274 查看
题目:国际象棋中的车可以水平或竖直移动。一个车从棋盘的一角(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 solution
count[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

;
}

public static void main(String[] args) {
System.out.println(cal(4));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: