马的移动 (BFS)

//题意自己看,不会度娘
#include <stdio.h>
#include <queue>
#include <string.h>
struct node
{
	int x;
	int y;
	int step;
};
int map[8][8];//标记数组 
int sx,sy,ex,ey,ans;
int move[8][2]={1,2,1,-2,-1,2,-1,-2,2,1,2,-1,-2,1,-2,-1};//方向数组控制方向 

int cheak(int x,int y)//检查是否符合要求 
{
	if(x<0||y<0||x>=8||y>=8)//是否越界 
		return 1;
	if(map[x][y])//已经使用过 
		return 1;
	return 0;	
}
void BFS()
{
	queue<node>we;//建立队列 
	node a,next;//建立结构体 
	a.x=sx;
	a.y=sy;//起点坐标赋值 
	a.step=0;//步数为0 
	map[sx][sy]=1;//标记为1代表已经走过 
	we.push(a);//放入 
	while(!we.empty())
	{
		a=we.front();
		we.pop();
		if(a.x==ex&&a.y==ey)
		{
			ans=a.step;
			return ;
		}//找到终点 
		for(int i=0;i<8;i++)//8方向循环 
		{
			next=a;
			next.x+=move[i][0];
			next.y+=move[i][1];
			if(cheak(next.x,next.y))
				continue;
			next.step=a.step+1;
			map[next.x][next.y]=1;
			we.push(next);
				
		}		
	}
	return ;
}

int main(int argc, char *argv[])
{
	char c1[10],c2[20];
	while(scanf("%s %s",c1,c2)!=EOF)
	{
		sx=c1[0]-'a';//坐标转化为字符型 
		sy=c1[1]-'1';//坐标转化为数字 
		ex=c2[0]-'a';//同上 
		ey=c2[1]-'1';
		memset(map,0,sizeof(map));
		BFS();
		printf("To get from %s to %s takes %d knight moves.\n",c1,c2,ans);
	}	
	return 0;
}
//Start-ZJ
//2017/10/23/11:25
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值