BFS

开篇警告:走图题千万千万别用dfs,很容易爆栈,死翘翘。
题目就像是个模板化的广度优先遍历的题目,在最普通的题目改成双向移动了,并且两个人都有各自移动的特点。一个走两步,一个走八个方向。
但是总结就是一个人能不能走到另外一个人走到过的路上。并且需要减枝一下,不然队列中元素太多,会爆栈。

Code

#pragma GCC target("avx,sse2,sse3,sse4,popcnt")
#pragma GCC optimize("O2,O3,Ofast,inline,unroll-all-loops,-ffast-math")
#include <bits/stdc++.h>
using namespace std;
#define js ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define all(vv) vv.begin(), vv.end()
#define endl "\n"
typedef long long ll; typedef unsigned long long ull; typedef long double ld;
const ll MOD = 1e9 + 7;
inline ll read() { ll s = 0, w = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') w = -1; for (; isdigit(ch); ch = getchar())    s = (s << 1) + (s << 3) + (ch ^ 48); return s * w; }
inline void write(ll x) { if (!x) { putchar('0'); return; } char F[40]; ll tmp = x > 0 ? x : -x; if (x < 0)putchar('-');    int cnt = 0;    while (tmp > 0) { F[cnt++] = tmp % 10 + '0';        tmp /= 10; }    while (cnt > 0)putchar(F[--cnt]); }
inline ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
ll qpow(ll a, ll b) { ll ans = 1;    while (b) { if (b & 1)    ans *= a;        b >>= 1;        a *= a; }    return ans; }    ll qpow(ll a, ll b, ll mod) { ll ans = 1; while (b) { if (b & 1)(ans *= a) %= mod; b >>= 1; (a *= a) %= mod; }return ans % mod; }
inline int lowbit(int x) { return x & (-x); }

const int N = 1000 + 7;
struct Node {
    int x, y;
};
char mp[N][N];
int vis[2][N][N];
queue<Node> q[2];
int dx[] = { 1,0,-1,0,1,1,-1,-1 };
int dy[] = { 0,1,0,-1,-1,1,-1,1 };
int cnt, n, m;

void bfs(int w) {
    int siz = q[w].size();
    while (siz--) {
        Node tmp = q[w].front(); q[w].pop();
        for (int i = 0; i < 4 + (w ? 0 : 4); ++i) {
            int xx = tmp.x + dx[i], yy = tmp.y + dy[i];
            if (xx > n or xx<1 or yy>m or yy < 1 or vis[w][xx][yy] or mp[xx][yy] == '#')
                continue;
            vis[w][xx][yy] = 1; q[w].push({ xx,yy });
            if (vis[w ^ 1][xx][yy]) {
                cout << "YES" << endl << cnt << endl;
                exit(0);
            }
        }
    }
}

int main() {
    js; cin >> n >> m;
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= m; ++j) {
            cin >> 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;
        }
    while (cnt <= n * m) {
        ++cnt; //时间戳+1
        bfs(0); //A动一下
        bfs(1); //B动两下
        bfs(1);
    }
    cout << "NO" << endl;
    return 0;
}