分部扩展小A和小B的移动范围,并判断是否能相遇。
当st[1][x][y] == st[2][x][y]就相遇
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 1e3 + 5;
char g[N][N];
bool st[2][N][N];
queue<pair<int, int>> q[2];
int n, m;
int x, y, x2, y2;
int dx[] = {0, 0, -1, 1, 1, -1, -1, 1};
int dy[] = {1, -1, 0, 0, 1, 1, -1, -1};
bool bfs(int t) {
int sz = q[t].size();
while(sz--){
auto p = q[t].front();
q[t].pop();
int x = p.first, y = p.second;
for(int i = 0; i < 4 + 4 * (!t); ++ i) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= n || nx < 0 || ny >= m || ny < 0) continue;
if(g[nx][ny] == '#' || st[t][nx][ny]) continue;
if(st[!t][nx][ny]) return true;
st[t][nx][ny] = true;
q[t].push({nx, ny});
}
}
return false;
}
int min_steps() {
q[0].push({x, y});
q[1].push({x2, y2});
st[0][x][y] = true;
st[1][x2][y2] = true;
int res = 0;
while(!q[0].empty()||!q[1].empty()) {
res ++;
if(bfs(0)) return res;
if(bfs(1)) return res;
if(bfs(1)) return res;
}
return -1;
}
int main() {
cin >> n >> m;
for(int i = 0; i < n; ++ i)
for(int j = 0; j < m; ++ j)
{
cin >> g[i][j];
if(g[i][j] == 'C') x = i, y = j;
if(g[i][j] == 'D') x2 = i, y2 = j;
}
int res = min_steps();
if(res == -1) puts("NO");
else {
puts("YES");
cout << res << endl;
}
return 0;
}