题意:
思路:
#include <cstdio>
#include <queue>
#include <iostream>
#include <stdlib.h>
using namespace std;
int cnt;
const int N = 1e3 + 10;
int dx[] = {1,-1,0,0,1,1,-1,-1},dy[] = {0,0,1,-1,1,-1,1,-1};
int n,m;
char mp[N][N];
bool vis[2][N][N];
queue< pair<int,int> > q[2];
void bfs(int op){
int sz = q[op].size();
while(sz--){
int x = q[op].front().first,y = q[op].front().second;
q[op].pop();
int up = (op == 0) ? 8 : 4;
for(int i = 0;i < up;i++){
int nx = x + dx[i],ny = y + dy[i];
if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && mp[nx][ny] != '#' && !vis[op][nx][ny]){
q[op].push({nx,ny});
vis[op][nx][ny] = 1;
if(vis[op^1][nx][ny]){
puts("YES");
printf("%d\n",cnt);
exit(0);
}
}
}
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i = 1;i <= n;i++){
for(int j = 1;j <= m;j++){
scanf(" %c",&mp[i][j]);
if(mp[i][j] == 'C') q[0].push({i,j}),vis[0][i][j] = 1;
else if(mp[i][j] == 'D') q[1].push({i,j}),vis[1][i][j] = 1;
}
}
//最多走n*m步,如果还没相遇则不可能相遇
while(cnt <= n*m){
++cnt;
bfs(0),bfs(1),bfs(1);
}
puts("NO");
return 0;
}