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