vjudge-Knight Moves(bfs)

Knight Moves

题目链接

https://vjudge.net/problem/UVA-439

题意描述:

给你一个起点一个终点,其实最少多少步能从起点走到终点,骑士只能走2*3的格子的对角线

解题思路:

广搜,把每个点遍历一下入队,找到了跳出即可

程序代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#include<queue>
struct data{
	int x;
	int y;
	int step;
};
char a,c,b,d;
int ex,ey;
int book[10][10];
int bfs();

int main() 
{ 
	while(scanf(" %c%c %c%c",&a,&b,&c,&d)!=EOF)
	{
		printf("To get from %c%c to %c%c takes %d knight moves.\n",a,b,c,d,bfs());
	}
	return 0;
}
int bfs()
{
	int i;
	int next[8][2]={-2,1, -1,2, 1,2, 2,1, 2,-1, 1,-2, -1,-2, -2,-1};
	
	queue<data>Q;
	data p,q;
	p.x=a-'a';
	p.y=b-'1';
	p.step=0;
	ex=c-'a';
	ey=d-'1';
	memset(book,0,sizeof(book));
	book[p.x][p.y]=1;
	Q.push(p);
	while(!Q.empty())
	{
		p=Q.front();
		Q.pop();
		if(p.x==ex&&p.y==ey)
			return p.step;
		for(i=0;i<8;i++)
		{
			q.x=p.x+next[i][0];
			q.y=p.y+next[i][1];
			if(q.x<0||q.x>=8||q.y<0||q.y>=8)
				continue;
			q.step=p.step+1;
			book[q.x][q.y]=1;
			Q.push(q); 
		}
	}
}

猜你喜欢

转载自blog.csdn.net/HeZhiYing_/article/details/86592541