Hust oj 1367 King(BFS)

King
Time Limit: 1000 MSMemory Limit: 65536 K
Total Submit: 129(84 users)Total Accepted: 91(83 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

问从起点到终点最少需要多少步

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
#include<map>
using namespace std;

const int maxn = 100;
int map[maxn][maxn];
int vis[maxn][maxn];
int re[maxn][maxn];
char Start[maxn];
char End[maxn];
int t;
int ans;
int sx,sy,ex,ey;
int fx[8] = {0,0,1,-1,1,1,-1,-1};
int fy[8] = {1,-1,0,0,-1,1,1,-1};
struct Point
{
    int x;
    int y;
};

Point start,nex,temp;

void bfs(int sx,int sy,int ex,int ey)
{
    queue<Point>Q;
    vis[sx][sy] = 1;
    start.x = sx;
    start.y = sy;
    Q.push(start);
    while(!Q.empty())
    {
        temp = Q.front();
        Q.pop();
        if(temp.x == ex && temp.y == ey) return;
        for(int i=0;i<8;i++)
        {
            nex.x = fx[i] + temp.x;
            nex.y = fy[i] + temp.y;
            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;
                re[nex.x][nex.y] = re[temp.x][temp.y] + 1;
                ans++;
                Q.push(nex);
            }
        }
    }
}

int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s",&Start);
        scanf("%s",&End);
        sx = Start[0] - 'a' + 1;
        sy = Start[1] - '0';
        ex = End[0] - 'a' + 1;
        ey = End[1] - '0';
        ans = 0;
        memset(vis,0,sizeof(vis));
        memset(re,0,sizeof(re));
        bfs(sx,sy,ex,ey);
        printf("%d\n",re[ex][ey]);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值