https://ac.nowcoder.com/acm/contest/549/G
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int[] dx = new int[] { 0, 0, 1, -1, 1, -1, 1, -1 };
static int[] dy = new int[] { -1, 1, 0, 0, 1, -1, -1, 1 };
static Queue<int[]>[] q = new Queue[2];
static int[][][] vis;
static int[][] maze;
static int N;
static int M;
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
N = scan.nextInt();
M = scan.nextInt();
maze = new int[N][M];
vis = new int[2][N][M];
q[0] = new LinkedList<>();
q[1] = new LinkedList<>();
int Ax = 0, Ay = 0, Bx = 0, By = 0;
// make maze
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
maze[i][j] = scan.next().charAt(0);
if (maze[i][j] == 'C') {
Ax = i;
Ay = j;
} else if (maze[i][j] == 'D') {
Bx = i;
By = j;
}
}
}
//
int ans = solve(Ax, Ay, Bx, By);
if (ans == -1)
System.out.println("NO");
else {
System.out.println("YES");
System.out.println(ans);
}
}
private static int solve(int Ax, int Ay, int Bx, int By) {
// TODO Auto-generated method stub
// 两个队列分别初始化
q[0].offer(new int[] { Ax, Ay });
vis[0][Ax][Ay] = 1;
q[1].offer(new int[] { Bx, By });
vis[1][Bx][By] = 1;
// 两个队列都空才停止
int time = 0;
while (!q[0].isEmpty() || !q[1].isEmpty()) {
++time;
if (bfs(0))
return time;
if (bfs(1))
return time;
if (bfs(1))
return time;
}
return -1;
}
private static boolean bfs(int t) {
// TODO Auto-generated method stub
int size = q[t].size();
while (size-- > 0) {
int[] cur = q[t].poll();
for (int i = 0; i < (t == 0 ? 8 : 4); ++i) {
int x = cur[0] + dx[i];
int y = cur[1] + dy[i];
if (x < 0 || y < 0 || x >= N || y >= M || maze[x][y] == '#' || vis[t][x][y] == 1)
continue;
// ans
if (vis[1 - t][x][y] == 1)
return true;
q[t].offer(new int[] { x, y });
vis[t][x][y] = 1;
}
}
return false;
}
}