BFS走一遍,将A与B分别放入两个队列中,每次将队列内的一层元素出队再进行下一层(将此步的可到达的地方全部都扩展到,保证两个队列同时扩展同一步。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <iomanip>
#include <queue>

using namespace std;

#define x first
#define y second

typedef pair<int, int> PII;

const int N = 1010;

int n, m;
char g[N][N];
bool st[2][N][N];
queue<PII> q[2];
int res;
int dx[8] = {-1, 0, 1, 0, -1, 1, 1, -1}, dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};

void print(int u) {
  for (int i = 0; i < n; i ++ ) {
    for (int j = 0; j < m; j ++ )
      cout << setw(5) << st[u][i][j];
    cout << endl;
  }
  puts("====================================");
}

bool bfs(int u) {
  int si = q[u].size();
  //将队列内这一层都要出队
  while (si --) {
    PII t = q[u].front();
    q[u].pop();

    for (int i = 0; i < (u ? 4 : 8); i ++ ) {
      int x = t.x + dx[i], y = t.y + dy[i];
      if (x >= 0 && x < n && y >= 0 && y < m && !st[u][x][y] && g[x][y] != '#') {
        if (st[u ^ 1][x][y]) return true;
        st[u][x][y] = true;
        q[u].push({x, y});
      }
    }
  }

  return 0;
}
int work() {
  while (q[0].size() || q[1].size()) {
    res ++;
    if (bfs(0)) return res;
    if (bfs(1)) return res;
    if (bfs(1)) return res;
  }

  return 0;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0); cout.tie(0);

  cin >> n >> m;
  for (int i = 0; i < n; i ++ )
    for (int j = 0; j < m; j ++ )
      cin >> g[i][j];

  for (int i = 0; i < n; i ++ )
    for (int j = 0; j < m; j ++ )
      if (g[i][j] == 'C') q[0].push({i, j}), st[0][i][j] = true;
      else if (g[i][j] == 'D') q[1].push({i, j}), st[1][i][j] = true;

  if (work()) cout << "YES\n" << res << endl;
  else cout << "NO" << endl;

  // print(0);
  // print(1);
}