我正在尝试使用作为on this site的bactracking来解决Knight Tour problem。为什么两个几乎相同的实现有很大的执行时间差?
网站takes about 0.49 seconds on ideone上给予实现。
int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[N],
int yMove[N])
{
int k, next_x, next_y;
if (movei == N*N)
return true;
/* Try all next moves from the current coordinate x, y */
for (k = 0; k < 8; k++)
{
next_x = x + xMove[k];
next_y = y + yMove[k];
if (isSafe(next_x, next_y, sol))
{
sol[next_x][next_y] = movei;
if (solveKTUtil(next_x, next_y, movei+1, sol, xMove, yMove) == true)
return true;
else
sol[next_x][next_y] = -1;// backtracking
}
}
return false;
}
虽然我实现的几乎相同的是。
int generateMoves(int x, int y, int moveNum, int soln[][N], int xMoves[], int yMoves[])//making move number 'moveNum' from x and y.
{
if(moveNum == N*N){
return 1;
}
else{
int i, nextX, nextY;
for(i=0; i<8; ++i){
nextX = x + xMoves[i];
nextY = y + yMoves[i];
if(isSafe(nextX, nextY, soln)){
soln[nextX][nextY] = moveNum;
if(generateMoves(nextX, nextY, moveNum+1, soln, xMoves, yMoves)){
return 1;
}
else{
soln[nextX][nextY] = -1;
}
}
}
return 0;
}
}
什么在我的代码中执行了这么久?
你有没有尝试分析你的代码,看看它花费的时间?在这两种情况下'isSafe'功能是否相同? – 2012-07-28 13:57:15
是的,isSafe在两者中都是一样的。请参阅我的完整代码http://ideone.com/RP068,其他代码在这里http://ideone.com/qfsf3 – Eight 2012-07-28 14:00:08
您的代码版本由于某种原因永远运行。看不出明显的原因。我建议再次查看代码,看看有什么不同。 – gnobal 2012-07-28 14:07:26