问题是:
给出精确的k步,从起点到目的地有多少种移动点的方法?点可以沿八个方向(水平,垂直,对角,反对角)移动。
我通过DP解决了该问题,但它仅适用于正方形板,不适用于矩形板。我的意思是,如果代码中的dim[0]!=dim[1]
,它将遇到错误结果。
在这里我可以提供测试用例:
测试用例1
dim = {5,6},start = {0,2},end = {2,2},steps = 4;
结果为50(预期为105)
测试案例2
dim = {5,5},int[] start = {0,2},end = {2,2},steps = 4;
结果为105(预期为105)
代码如下:
private static int[][] dir = {{0,1},{1,0},{1,1},{1,-1},{0,-1},{-1,0},{-1,-1},{-1,1}};
//DP
/*
@param dim, a tuple (width, height) of the dimensions of the board
@param start, a tuple (x, y) of the king's starting coordinate
@param target, a tuple (x, y) of the king's destination
*/
public static int countPaths2(int[] dim, int[] start, int[] des, int steps){
if(dim[0] == 0 || dim[1] == 0) return 0;
int[][][] dp = new int[dim[0]*dim[1]][dim[1]*dim[0]][steps+1];
for(int step = 0; step<=steps;step++){
for(int i = 0; i< dim[0]*dim[1];i++){
for(int j = 0; j< dim[0]*dim[1];j++){
if(step == 0 && i == j){
dp[i][j][step] = 1;
}
if(step >= 1){
for(int k =0; k< dir.length;k++){
int row = i / dim[0];
int col = i % dim[1];
if(row + dir[k][0] >= 0 && row + dir[k][0]< dim[0] && col + dir[k][1]>=0 && col + dir[k][1]< dim[1]){
int adj = (row + dir[k][0])*dim[0] + col + dir[k][1];
dp[i][j][step] += dp[adj][j][step-1];
}
}
}
}
}
}
int startPos = start[0]*dim[0] + start[1];
int targetPos = des[0]*dim[0] + des[1];
return dp[startPos][targetPos][steps];
}
public static void main(String[] args){
int[] dim = {5,5}; // can just use to square;
int[] start = {0,2};
int[] end = {2,2};
int steps = 7;
System.out.println(countPaths2(dim, start,end, steps));
}
我如何使其适用于任何类型的电路板?
答案 0 :(得分:1)
罪魁祸首是:
int row = i / dim[0];
int col = i % dim[1]; // <- this should have been dim[0]
在div / mod模式中,您应该用相同的数字除和取模...