AcWing 1102. 移动骑士
原题链接
简单
作者:
哈哈哈hh
,
2020-06-27 17:51:21
,
所有人可见
,
阅读 600
标准bfs (菜鸡一枚 比较标准的)
#include <iostream>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 310;
int T;
int n;
int m;
typedef pair<int,int> PII;
int dis[N][N];
bool st[N][N];
int x;
int y;
int endx;
int endy;
static int pos[8][2] = {{1,2},{2,1},{2,-1},{1,-2},{-1,2},{-2,1},{-2,-1},{-1,-2}};
int bfs()
{
memset(st,false,sizeof st);
memset(dis,0,sizeof dis);
queue<PII> q;
q.push({x,y});
st[x][y] = true;
dis[x][y] = 0;
while(!q.empty())
{
auto tmp = q.front();
q.pop();
if(tmp.first == endx && tmp.second == endy)
{
return dis[tmp.first][tmp.second];
}
for(int i = 0 ; i < 8; i++)
{
int nx = tmp.first + pos[i][0];
int ny = tmp.second + pos[i][1];
if(nx < 0 || nx >= n || ny < 0 || ny >= n || st[nx][ny] == true)
continue;
q.push({nx,ny});
st[nx][ny] =true;
dis[nx][ny] = dis[tmp.first][tmp.second] + 1;
}
}
return 0;
}
int main()
{
cin >> T;
while(T--)
{
cin >> n;
cin >> x >>y;
cin >> endx >> endy;
cout << bfs() << endl;
}
}