1015

题目编号:1015

题目大意:一个8*8的棋盘,骑士只能走日字型,求从给定的起点和终点需要走的最少步数。

解题思路:没什么特别的,就是广搜。创建结构体,内涵行列和步数,用队列来进行存储。先表示出来起点终点的行列坐标,然后广搜即可。

做题感想:看到这个题,我一下子想到老师的例题了,不过有所区别,老师的是给定的棋盘大小,这个是固定的,然后稍微修改就可以了,方法都是一般的广搜,剪枝也大同小                           异。

#include<iostream>
#include<queue>
using namespace std;
typedef struct point{
	int x,y;
	int moves;
}point;
queue<point>Q;
int e_x,e_y;
int map[10][10];
int dir[8][2]={{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2}};
int i,j,ans,x,y;
point start;
string s;
int bfs(point s)
{
	map[s.x][s.y]=1;
	point head,t;
	Q.push(s);
	while(!Q.empty ())
	{
		head=Q.front();
		Q.pop();
		if(head.x==e_x&&head.y==e_y)
		   return head.moves;
		for(i=0;i<8;i++)
		{
			x=head.x+dir[i][0];
                           y=head.y+dir[i][1];
			if(x>=0&&x<8&&y>=0&&y<8&&!map[x][y])
			{
				map[x][y]=1;
				t.x=x;
				t.y=y;
				t.moves=head.moves+1;
				Q.push(t);
			}
		}
	}
}
int main()
{
	while(1)
	{
		cin>>s;
		memset(map,0,sizeof(map));
			while(!Q.empty())
				Q.pop();
		start.x=s[0]-'a';
		start.y=s[1]-'1';
		e_x=s[3]-'a';
		e_y=s[4]-'1';
		start.moves=0;
		ans=bfs(start);
		cout<<"To get from "<<s[0]<<s[1]<<" to "<<s[3]<<s[4]<<" takes "<<ans<<" knight moves."<<endl;
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值