为什么两个几乎相同的实现有很大的执行时间差

why two almost same implementation is having a big execution time difference?

本文关键字:实现 时间差 执行时间 执行 两个 为什么      更新时间:2023-10-16

我正试图使用本网站上给出的细菌追踪来解决骑士团的问题。

在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};

顺序不同。你在纸上画出可能的动作,你会发现正确的动作是逆时针的,而你的动作则完全混乱
这一定是造成你问题的原因。