当前位置: 代码迷 >> 综合 >> UVa - 439 - Knight Moves(bfs求最短路)
  详细解决方案

UVa - 439 - Knight Moves(bfs求最短路)

热度:58   发布时间:2023-10-09 18:11:58.0

UVa - 439 - Knight Moves(bfs求最短路)

UVa - 439 - Knight Moves(bfs求最短路)



#include<iostream>
#include<queue>
#include<string>
#include<cstring>
using namespace std;
int x1,y1,x2,y2,ans;
string str1,str2;
//用来标记是否已经访问过 
int vis[10][10];
//八个方向 
int dis[8][2] = {-1,2 ,1,2 ,2,1 ,2,-1 ,1,-2 ,-1,-2 ,-2,-1 ,-2,1}; 
struct Step{int x,y,steps;		//x和y表示左边点,steps表示到达该点的最少步数 
};void bfs(){//起点==终点 if(x1==x2&&y1==y2){ans = 0;return ;}//起点入队 queue<Step>q;Step s1;s1.x=x1;s1.y=y1;s1.steps=0;vis[x1][y1] = 1;q.push(s1);while(!q.empty()){Step s2;//八个方向遍历 for(int i=0 ;i<8 ;i++){s2.x = q.front().x+dis[i][0];s2.y = q.front().y+dis[i][1];s2.steps = q.front().steps+1;	if(vis[s2.x][s2.y]==1||s2.x<0||s2.y<0||s2.x>7||s2.y>7){continue;}else{vis[s2.x][s2.y]=1;q.push(s2);//如果遍历中到达了终点 则跳出 if(s2.x==x2&&s2.y==y2){break;}}}//获取答案 跳出while循环 if(s2.x==x2&&s2.y==y2){ans = s2.steps;break;}q.pop();}}int main(){while(cin>>str1>>str2){memset(vis,0,sizeof(vis));x1 = (int)str1[0]-'a';y1 = (int)str1[1]-'0'-1;x2 = (int)str2[0]-'a';y2 = (int)str2[1]-'0'-1;bfs();cout<<"To get from "<<str1<<" to "<<str2<<" takes "<<ans<<" knight moves.\n";}return 0;
}