1、描述

2、思路
广度优先,
定义8个方向
6、code
#include<iostream>
#include<queue>
using namespace std;
int dir[8][2]={{1,2},{2,1},{1,-2},{-2,1},{-1,2},{2,-1},{-2,-1},{-1,-2}};
int vis[12][12]={0};
using namespace std;
struct point
{
int x,y;
int step;
};
point S,E;
queue<point>q;
int bfs()
{
while(!q.empty()) //清空队列
q.pop();
S.step=0;
q.push(S);
vis[S.x][S.y]=1;
while(!q.empty())
{//每一轮依次将队列里的元素出队查看是否到达终点,如是则return,否就将该点8个方向上的点依次入队
point cur=q.front();
q.pop();
if(cur.x==E.x&&cur.y==E.y)
return cur.step;
for(int i=0;i<8;i++)
{
point nxt;
nxt.x=cur.x+dir[i][0];
nxt.y=cur.y+dir[i][1];
nxt.step=cur.step+1;
if(nxt.x<1||nxt.x>8||nxt.y<1||nxt.y>8) //超出棋盘边界
continue;
if(vis[nxt.x][nxt.y]==1) //该点经过
{
continue;
}
q.push(nxt);
}
}
return -1;
}
int main()
{
int x1,y1;
string a,b;
cout<<"提示:输入 '#' 退出程序!!!"<<endl;
while(cin>>a&&a!="#")
{
cin>>b;
//cout<<a<<" "<<b<<endl;
S.x=a[1]-'0';
S.y=a[0]-'a'+1;
E.x=b[1]-'0';
E.y=b[0]-'a'+1;
//cout<<x2<<" "<<y2<<endl;
if(a==b)
cout<<a<<"==>"<<b<<": "<<0<<" moves"<<endl;
else
{
cout<<a<<"==>"<<b<<": "<<bfs()<<" moves"<<endl;
}
}
return 0;
}
版权声明:本文为Tlwhisper原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。