题意:给定一个n*n的棋盘,一个起点坐标,一个终点坐标。问从起点“走日”到终点的最少步数。走日即象棋里的马走日。(2243题意完全相同,只不过棋盘限制在8*8)
思路:bfs水题。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <cstdlib>
using namespace std;
#define clc(s,t) memset(s,t,sizeof(s))
#define INF 0x3fffffff
#define N 305
int s[N][N],flag[N][N];
int T,n;
int a,b,x,y;
int ori[8][2] = {{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2}};
struct node{
int x,y,t;
node(int xx,int yy,int tt):x(xx),y(yy),t(tt){};
};
queue<struct node>q;
int check(int x,int y){
return x>=0&&y>=0&&x<n&&y<n;
}
int bfs(){
while(!q.empty()){
struct node now = q.front();
q.pop();
if(now.x == x && now.y == y)
return now.t;
for(int i = 0;i<8;i++){
int xx = now.x+ori[i][0];
int yy = now.y+ori[i][1];
if(check(xx, yy) && !flag[xx][yy]){
q.push(node(xx,yy,now.t+1));
flag[xx][yy] = 1;
}
}
}
return -1;
}
int main(){
scanf("%d",&T);
while(T--){
while (!q.empty())
q.pop();
clc(flag, 0);
scanf("%d",&n);
scanf("%d %d %d %d",&a,&b,&x,&y);
q.push(node(a,b,0));
flag[a][b] = 1;
printf("%d\n",bfs());
}
return 0;
}