骑士游历问题 合肥工业大学 程序设计艺术实验二
运用DFS 应该不用写思路了⑧
有问题可以直接加学长qq:396434855
加QQ先发3元红包哦 讲解包宁满意
学妹不要钱~~(开个玩笑)
程序源码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int MAX_SIZE = 8;//八行八列的棋盘
int sum = 0;//遍历的次数
int vis[MAX_SIZE][MAX_SIZE] = {
0};//已走过的点设为1
typedef struct p
{
int x, y;
}Point;//点
vector<Point> points;//存储走过的点
bool inside_judge(const Point & pos)
{
return 0 <= pos.x && pos.x < MAX_SIZE && 0 <= pos.y && pos.y < MAX_SIZE;
}//判断当前走的点是否越界
bool dfs(const Point &now)
{
points.push_back(now);//当前点进入容器
sum++;//遍历次数加1
if(sum == 64) return true;//所有点均已遍历 结束
const int dir[8][2] = {
{
-1, 2}, {
-2, 1}, {
-2, -1}, {
-1, -2},
{
1, 2}, {
2, 1}, {
2, -1}, {
1, -2}};//定义可以走的八个方向
for(int ind = 0; ind < 8; ind++){
//对八个方向进行遍历
Point next = now;
next.x += dir[ind][0];
next.y += dir[ind][1]; //下一个点的坐标
if(inside_judge(next) && 0 == vis[next.x][next.y])//下一个点不越界 且没走过
{
vis[next.x][next.y] = 1;//标记已经走过
if(dfs(next))//从下一个点开始搜索
{
return true;
}
vis[next.x][next.y] = 0;//如果下一个点遍历失败 则将下一个点从已经走过中抹去
}
}
points.pop_back();//遍历失败则将当前点拿出容器
sum--;//遍历失败则容器中点的个数减一
return false;
}
int main()
{
int x, y;
cout << "请输入起始坐标:";
cin >> x >> y;
Point point;
point.x = x;
point.y = y;
vis[x][y] = 1;//标记起点
dfs(point);
vector<Point>:: iterator it = points.begin();
int i = 0;
while(it != points.end())
{
i++;
cout << "第" << i << "步 : ";
cout << "(" << it -> x << "," << it -> y << ")" <<endl;
it++;
}
return 0;
}
运行截图