深度优先搜索DFS
来源:互联网 发布:青山大禹软件 编辑:程序博客网 时间:2024/05/29 03:19
题目:一个棋盘格9*10,按照象棋马走“日”的规则,从起点走到终点,且走过的路不能重新走,设计一个算法实现!
分析:
本题是典型的深度优先搜索的题目,首先分析马在一个位置时所能走的下一个位置时的走法,共有8种。如下图所示马所在位置所能到达的地方:
移动规则为:
int dx[] = {2,1,-1,-2,-2,-1,1,2};int dy[] = {1,2,2,1,-1,-2,-2,-1};
每次所能移动的位置的变量约束关系如上。具体如下代码所示:
#include<iostream>#include<vector>#include<string>#include<algorithm>#include<queue>using namespace std;struct horse{ //定义一个马 int sx,sy; int iSetp;};bool visit[9][10]={0}; //定义 9*10大小的棋盘格int dx[] = {2,1,-1,-2,-2,-1,1,2};int dy[] = {1,2,2,1,-1,-2,-2,-1};bool Horse(int sx,int sy,int ex,int ey) // 主要程序{ horse hor; if(sx<0 || sx>8 || sy<0 || sy>9 || ex<0 || ex>8 || ey<0 ||ey>9) { cout<<"Error!"<<endl; return false; } hor.sx = sx; hor.sy = sy; queue<horse> d; d.push(hor); if(hor.sx == ex && hor.sy == ey) return true; visit[sx][sy] = true; while(hor.sx != ex || hor.sy != ey) { for(int i = 0 ; i < 8;i++) { hor = d.front(); //horse temp1; cout<<"front:"<<hor.sx<<"::"<<hor.sy<<endl; hor.sx += dx[i]; hor.sy += dy[i]; if(hor.sx < 0 || hor.sx >=9 || hor.sy < 0 || hor.sy >=10) continue; if(9>hor.sx>=0 && 10>hor.sy>=0) { if(visit[hor.sx][hor.sy] != true) { d.push(hor); cout<<"d :"<<hor.sx<<"::"<<hor.sy<<endl; if(hor.sx == ex && hor.sy == ey) return true; visit[hor.sx][hor.sy] = true; } } } d.pop(); if(d.empty()) { return false; } hor = d.front(); }}int main(int argc,char** argv){ bool temp = Horse(8,9,8,8); cout<<"result = "<<temp<<endl; system("pause"); return 0;}
Output:
阅读全文
0 0
- 深度优先搜索 DFS
- 深度优先搜索 DFS
- DFS 深度优先搜索
- DFS 深度优先搜索
- 深度优先搜索(DFS)
- 深度优先搜索(DFS)
- 深度优先搜索DFS
- DFS深度优先搜索
- 深度优先搜索(DFS)
- dfs深度优先搜索
- dfs 深度优先搜索
- 深度优先搜索(DFS)
- 深度优先搜索DFS
- DFS深度优先搜索
- 深度优先搜索(DFS)
- 深度优先搜索DFS
- 深度优先搜索(DFS)
- 深度优先搜索--DFS
- private 继承(effective C++ 条款40)
- 数据结构 第八章 排序
- 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛
- 最近的计划
- 阿里云服务器配置(二)
- 深度优先搜索DFS
- java可重入锁(ReentrantLock)的实现原理
- Spring MVC--16.参数接受map
- 配置wordpress时出现403 Forbidden nginx/1.10.2
- python3 利用pip安装ipython notebook
- java面试题02
- 微信公众号----微信支付踩坑
- Redis实战(一) 使用缓存合理性
- 04 Activity窗口间的切换及参数的传递