[英]Big difference (x9) in the execution time between almost identical code in C and C++
[英]why two almost same implementation is having a big execution time difference?
我正在嘗試使用本網站上給出的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;
}
而我執行的幾乎相同的操作顯示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;
}
}
在我的代碼中執行了這么長時間的東西是什么?
更改xMoves / yMoves似乎可行: ideone 。 這可能只是導致其較早找到解決方案的搜索順序。
63、62、61等長度的巡回演出太多,無法達到最終剩余的平方。 在最壞的情況下,必須進行蠻力搜索。 通過嘗試一系列導致較早解決方案的動作,該算法一直很幸運。
您的帖子沒有顯示您的代碼與原始代碼之間的區別。
實際上,如果仔細看一下代碼,則您的代碼與正確的代碼之間只有這樣的代碼:
int xMoves[] = { 2, 1, -1, -2, -2, -1, 1, 2 };//{2, 2, 1, 1, -1, -1, -2, -2};
int yMoves[] = { 1, 2, 2, 1, -1, -2, -2, -1 };//{1, -1, -2, 2, -2, 2, -1, 1};
順序是不同的。 您在紙上畫出可能的移動,然后發現正確的移動具有逆時針順序,而您的移動則完全處於混亂狀態。
那一定是引起您問題的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.