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;
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值