为什么两个几乎相同的实现有很大的执行时间差
why two almost same implementation is having a big execution time difference?
我正试图使用本网站上给出的细菌追踪来解决骑士团的问题。
在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};
顺序不同。你在纸上画出可能的动作,你会发现正确的动作是逆时针的,而你的动作则完全混乱
这一定是造成你问题的原因。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 为什么这两个实现多维数组之间会有如此巨大的执行时间差
- 为什么两个几乎相同的实现有很大的执行时间差