나는 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;
}
거의 동일 내게로 구현 한 동안 showing time limit exceeded(more than 5 seconds) on ideone입니다.
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' 함수는 두 경우 모두 동일합니까? –
예, isSafe는 both.please에서 동일합니다. 여기서 전체 코드는 http://ideone.com/RP068을 참조하고 다른 코드는 http://ideone.com/qfsf3 – Eight
코드의 버전은 어떤 이유로 영원히 실행됩니다 . 명백한 이유를 알 수 없습니다. 코드를 다시 살펴보고 그 차이점을 확인하는 것이 좋습니다. – gnobal