Title link: https://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=1342
Topic
Two knights can only walk in a square pattern. They walk at the same time on a plane of length n and width m , and ask if they can meet.
The plane contains three elements: "." "#" "K", the dot indicates a good flat ground, the pound sign indicates a bad flat ground, and K indicates a knight.
Ideas
Run two bfs and record the number of steps required by the two knights to reach the ij plane. If they do not have overlapping areas, they will definitely not meet.
Then if the two can walk to this flat ground, it does not mean that they will meet. It may also be the case that the front foot goes out and the back foot goes in.
Therefore, it is necessary to judge whether the difference in the number of steps taken by the two knights to this land is an even number. If it is an even number, then the fast knight can run back and forth, and they will always meet.
You can also walk on bad land!
ac code
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ok(x, y) x >= 1 && x <= 8 && y >= 1 && y <= 8
int dx[] = {-2, -2, 2, 2};
int dy[] = {-2, 2, -2, 2};
int dep1[15][15], dep2[15][15];
char a[15][15];
struct node{
int x, y;
};
void bfs1(int x, int y){
queue<node> q;
q.push({x, y});
dep1[x][y] = 0;
while(q.size()){
node tt = q.front(); q.pop();
for(int i = 0; i < 4; i ++){
int tx = tt.x + dx[i];
int ty = tt.y + dy[i];
if(ok(tx, ty) && dep1[tt.x][tt.y] + 1 < dep1[tx][ty]){
dep1[tx][ty] = dep1[tt.x][tt.y] + 1;
q.push({tx, ty});
}
}
}
}
bool bfs2(int x, int y){
queue<node> q;
q.push({x, y});
dep2[x][y] = 0;
while(q.size()){
node tt = q.front(); q.pop();
if(dep1[tt.x][tt.y] != 0x3f3f3f3f && (dep1[tt.x][tt.y] - dep2[tt.x][tt.y]) % 2 == 0){
return true;
}
for(int i = 0; i < 4; i ++){
int tx = tt.x + dx[i];
int ty = tt.y + dy[i];
if(ok(tx, ty) && dep2[tt.x][tt.y] + 1 < dep2[tx][ty]){
dep2[tx][ty] = dep2[tt.x][tt.y] + 1;
q.push({tx, ty});
}
}
}
return false;
}
int main(){
int t; scanf("%d", &t);
while(t --){
vector<node> k;
memset(dep1, 0x3f3f3f3f, sizeof(dep1));
memset(dep2, 0x3f3f3f3f, sizeof(dep2));
for(int i = 1; i <= 8; i ++){
scanf("%s", a[i] + 1);
for(int j = 1; j <= 8; j ++){
if(a[i][j] == 'K') k.push_back({i, j});
}
}
queue<node> q;
int x, y, flag = 0;
x = k[0].x, y = k[0].y;
bfs1(x, y);
x = k[1].x, y = k[1].y;
if(bfs2(x, y)) puts("YES");
else puts("NO");
}
return 0;
}