Eig*_*ght 0 c c++ performance execution-time
我正在尝试使用本网站上给出的bactracking 解决Knight Tour问题.
在网站上给出的实现 在ideone上大约需要0.49秒.
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;
}
Run Code Online (Sandbox Code Playgroud)
而我实施的几乎相同的一个显示超过了ideone的时间限制(超过5秒).
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;
}
}
Run Code Online (Sandbox Code Playgroud)
什么在我的代码中执行了这么久?