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

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);
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值