您的位置:首页 > 其它

哈理工OJ 1367 King【基础入门BFS】

2016-02-15 18:26 489 查看
King
Time Limit: 1000 MSMemory Limit: 65536 K
Total Submit: 122(80 users)Total Accepted: 87(79 users)Rating: 





Special Judge: No
Description
The king in the chessboard wonders the least number of moves to go to square t from squares. The king can move one square at a time in any direction (8 directions).



Help him to solve this problem!

Input
There are multiple test cases. The first line of input is an integer T indicating the number of test cases. Then T test cases follow.
For each test case:
Line 1. This line contains the chessboard coordinates of position s indicating the square the king is currently in.
Line 2. This line contains the chessboard coordinates of position t indicating the square the king wants to go to.
The coordinate consists of a lowercase letter from a to h and a digit from 1 to 8.
Output
For each test case:
Line 1. Output the least number of moves.
Sample Input
1

a1

h8

Sample Output
7

Source
哈理工2012春季校赛 - 网络预选赛
入门级BFS题目、注意边界是8*8即可:

另外注意处理输入的部分,把a变成1,把h变成8那样修改输入就行了、

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
struct zuobiao
{
int x,y;
}now,nex;
int ex,ey;
int sx,sy;
int vis[9][9];
int output[9][9];
int fx[8]={-1,-1,0,1,1,1,0,-1};
int fy[8]={0,1,1,1,0,-1,-1,-1};
void bfs(int x,int y)
{
queue<zuobiao >s;
memset(output,0,sizeof(output));
memset(vis,0,sizeof(vis));
vis[x][y]=1;
now.x=x;
now.y=y;
s.push(now);
while(!s.empty())
{
now=s.front();
if(now.x==ex&&now.y==ey)
{
printf("%d\n",output[now.x][now.y]);
return ;
}
s.pop();
for(int i=0;i<8;i++)
{
nex.x=now.x+fx[i];
nex.y=now.y+fy[i];
if(nex.x>=1&&nex.x<=8&&nex.y>=1&&nex.y<=8&&vis[nex.x][nex.y]==0)
{
vis[nex.x][nex.y]=1;
output[nex.x][nex.y]=output[now.x][now.y]+1;
s.push(nex);
}
}
}
return ;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[3],b[3];
scanf("%s%s",a,b);
sx=(a[0]-'a')+1;
sy=a[1]-'0';
ex=b[0]-'a'+1;
ey=b[1]-'0';
bfs(sx,sy);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息