循环无限运行C++解决骑士之旅问题
Loop running infinitely C++ for Knight Tour Problem
我正在用C++编写Knight Tour问题。但它正在无限期地运行。我检查了我的逻辑,与这里提到的逻辑相似
#include<bits/stdc++.h>
using namespace std;
bool isvalid(vector<vector<int>>board,int i,int j)
{
return i >= 0 && j >= 0 && i < 8 && j < 8 ;
};
bool checkcompletion(vector<vector<int>>board)
{
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
if(board[i][j]==0)
return false;
}
return true;
}
int tour(vector<vector<int>>board,int i,int j,int steps)
{
//CHECK IF IT IS A VALID STEP IF NOT VALID THEN RETURN 0
if(!isvalid(board,i,j))
{
return 0;
}
//CHECK IF THAT PLACE IS ALREADY VISITED(MOVED OUT OF ISVALID AS THAT FUNCTION ME
//GET A OUT OF BOUND REQUEST WHICH WILL CAUSE SEGMENTATION FAULT)
// cout<<i<<" "<<j<<endl;
if(board[i][j]!=0) return 0;
//CHECK IF ALL ARE MARKED FOR TERMINATION
if(steps==64)return 1;
//if(checkcompletion(board)) return 1;
//BACKTRACKING IDEA VARIABLE
board[i][j]=++steps;
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
if(board[i][j]>9)
cout<<" "<<board[i][j]<<" ";
else
cout<<" "<<board[i][j]<<" ";
}
cout<<"n";
}
cout<<"================================n";
tour(board,i+2,j+1,steps);
tour(board,i+1,j+2,steps);
tour(board,i-1,j+2,steps);
tour(board,i-2,j+1,steps);
tour(board,i-2,j-1,steps);
tour(board,i-1,j-2,steps);
tour(board,i+1,j-2,steps);
tour(board,i+2,j-1,steps);
board[i][j]=0;
}
int main()
{
//for marking the visited part as well as noting the number os steps
vector<vector<int>>board (8,vector<int>(8,0));
int steps = 0;
//MADE steps =1 for 0,0
//board[0][0]=++steps;
//initil position 0,0
tour(board,0,0,steps);
}
有人能告诉我这个代码出了什么问题吗?当我检查数组的中间状态时,它运行得很好。是因为算法很复杂,因此运行时间更长,而我把它误认为是一个无限循环吗?我检查了这个答案,它描述了这个问题有多复杂
您试图做的是递归函数,但您没有退出条件,因此函数在循环中调用自己。您应该根据函数的目标在函数中的某个位置放置一个return。例如:
if (tour(board, i + 2, j + 1, steps) == 0)
{
return steps;
}
(这是一个例子,我不知道你的情况如何(
如果你想了解更多关于递归函数的信息,这里有网站:
https://beginnersbook.com/2017/08/cpp-recursion/#:~:text=%20进程%20in%20which%20a,f(n(%20%3D%201。
https://www.geeksforgeeks.org/recursion/
此外,我建议您使用调试器来了解代码被卡住的原因和位置。
希望有帮助:(
相关文章:
- 将依赖名称显式标记为类型名和模板的奇怪之处
- 循环无限运行C++解决骑士之旅问题
- 为什么堆栈和堆在内存中分离得如此之多?
- 代码厨师问题伊什瓦拉(应许之地)
- 关于int :0有什么特别之处在C++
- C++ 分而治之的算法问题
- 为什么 Lisp 中 1000 阶乘的计算如此之快(并显示正确的结果)?
- 以下示例中给出的构造有什么不幸之处?
- 在国际象棋骑士巡回赛中遇到困难
- 国际象棋骑士巡回赛使用递归回溯
- 使用分而治之的最大总和子数组,为什么要以不同的方式使用 for 循环,答案是错误的?
- C++用死亡之钻印刷
- 使用堆栈的骑士之旅C++
- 骑士之旅暴力递归
- 骑士之旅 c++ 递归
- 使用递归的骑士之旅
- 使用递归的 C++ 中的骑士之旅
- 骑士之旅异常行为
- 用 c++ 解决骑士之旅
- 使用回溯的代码骑士之旅未显示任何输出