uva 439 Knight Moves 骑士移动

这道题曾经写过,bfs。用队列,不多说了,上代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<queue>
using namespace std;
int map[10][10];
int visit[10][10];
int dist[10][10];
int dx[8]={-2,-2,-1,-1,1,1,2,2};
int dy[8]={-1,1,-2,2,-2,2,-1,1}; 
char a[5];
int x2,y2;
struct node
{
	int x,y;
};
queue<node>q; 
int bfs(node T)
{
	if(T.x==x2&&T.y==y2)
	{
		return dist[T.x][T.y];
	}
	else
	{
		while(!q.empty())
		{
			node m = q.front();
			q.pop();
			if(m.x==x2&&m.y==y2)
				return dist[m.x][m.y];
			for(int i=0; i<8; i++)
			{
				
				int xx = m.x+dx[i];
				int yy = m.y+dy[i];
				if(!visit[xx][yy]&&xx>0&&yy>0&&xx<=8&&yy<=8)
				{
					node n ;
					n.x = xx;
					n.y = yy;
					q.push(n);
					dist[xx][yy] = dist[m.x][m.y]+1;
					visit[xx][yy] = 1;
				}
			}
		}
	}
}
int main()
{
	int x1,y1,i,j;
	while(gets(a))
	{
		y1 = a[0]-'a'+1;
		x1 = a[1]-'0';
		y2 = a[3]-'a'+1;
		x2 = a[4]-'0';
		//printf("%d %d %d %d\n",x1,y1,x2,y2);
		node T;
		T.x = x1;
		T.y = y1;
		memset(dist,0,sizeof(dist));
		memset(visit,0,sizeof(visit));
		q.push(T);
		bfs(T);
		printf("To get from %c%c to %c%c takes %d knight moves.\n",a[0],a[1],a[3],a[4],dist[x2][y2]);
		while(!q.empty())
		{
			q.pop();
		} 
	}
	return 0;
}
 


转载于:https://www.cnblogs.com/yfceshi/p/6895347.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值