chess

There is a mobile piece and a stationary piece on the N×M chessboard. The available moves of the mobile piece are the same as set out in the image below. You need to capture the stationary piece by moving the mobile piece with the minimum amount of moves


Write a program to find out the minimum number moves to catch a piece

[I/O Example]

Input
2
9 9
3 5 2 8
20 20
2 3 7 9

Output
2

5


#include<iostream>

#include<queue>
#include<vector>
using namespace std;
typedef struct
{
    int x;
    int y;
    int step;
}Node;


int T;
int N,M;
queue<Node>Queue;


int dir[8][2]={{-2,-1},{-2,1},{2,-1},{2,1},{1,-2},{1,2},{-1,-2},{-1,2}};
int main()
{
    //freopen("sample_input.txt", "r", stdin);
    int test_case = 0;
    cin>>T;
    Node startNode,endNode,currentNode,tempNode;
    for(int test_case=0;test_case<T;test_case++)
    {
        cin>>N>>M;
        cin>>startNode.x>>startNode.y>>endNode.x>>endNode.y;

        vector<int> tmpVect(M+1, 0);
        vector<vector<int> > flagVisit(N+1, tmpVect);

        startNode.step = 0;
        flagVisit[startNode.x][startNode.y] = 1;
        Queue.push(startNode);
        int minStep = -1;
        while(!Queue.empty())
        {
            currentNode = Queue.front();
            Queue.pop();
            for(int i = 0;i<8;i++)
            {
                if(currentNode.x == endNode.x && currentNode.y == endNode.y)
                {
                    minStep = currentNode.step;
                    break;
                }
                int xx = currentNode.x + dir[i][0];
                int yy = currentNode.y + dir[i][1];
                if(xx >= 1 && yy >= 1&& xx <= M && yy<=N &&flagVisit[xx][yy] == 0)
                {
                    //入队列
                    tempNode.x = xx;
                    tempNode.y = yy;
                    tempNode.step = currentNode.step + 1;
                    flagVisit[tempNode.x][tempNode.y] = 1;
                    Queue.push(tempNode);
                }
            }
        }
        cout<<minStep<<endl;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值