水题,与马的遍历相同
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#define x first
#define y second
using namespace std;
const int N = 210;
typedef pair<int,int> pii;
pii q[N *N];
int g[N][N];
int dx[] = {-2,-1,1,2,2,1,-1,-2,-2,2,2,-2};
int dy[] = {1,2,2,1,-1,-2,-2,-1,2,2,-2,-2};
int n,m;
bool st[N][N];
int dis[N][N];
int xa,ya,xb,yb;
void bfs(int sx, int sy){
memset(st,0,sizeof(st));
memset(dis,-1,sizeof(dis));
dis[sx][sy] = 0;
int hh = 0, tt = 0;
q[0] = {sx,sy};
st[sx][sy] = true;
while(hh <= tt){
pii t = q[hh++];
for(int i = 0; i < 12; i++){
int a = t.x + dx[i], b = t.y + dy[i];
if(a >= 1 && a <= 20 && b >= 1 && b <= 20 && !st[a][b] && dis[a][b] == -1){
dis[a][b] = dis[t.x][t.y] + 1;
q[++tt] = {a,b};
}
}
}
}
int main(){
cin >> xa >> ya >> xb >> yb;
bfs(xa,ya);
cout << dis[1][1] << endl;
bfs(xb,yb);
cout << dis[1][1];
}