代码略长包涵 luogu oj全ae,蓝桥vip oj可以下载输入输出样例,自己在试过,全ac,但是蓝桥vip oj也是re,New OJ也是全re, 只有蓝桥练习ac不知道什么原因
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
/**
* ClassName: 穿越雷区
* Package: com.搜索
* Describe:https://www.luogu.com.cn/problem/P8628
*
* @Create 2023/03/30 11:34
*/
public class Main {
static int n,ans = Integer.MAX_VALUE;static char[][] map;static int[][] vis;static Pos A,B; static int[][] steps ;
static int ts = 0;
public static void main(String[] args) throws Exception {
// 输入
n = nextInt(); map = new char[n][n]; vis = new int[n][n];steps = new int[n][n];
for(int i = 0; i < n; i++){
String row = bf.readLine();
for(int j = 0,k = 0; k < n; j++){
char c = row.charAt(j);if(c == ' ')continue;
map[i][k] = row.charAt(j); if(map[i][k] == 'A') A = new Pos(i,k); if(map[i][k] == 'B') B = new Pos(i,k);k++;
}
}
// 从A点出发两种路径 清空状态走第二种
bfs(A,1);vis = new int[n][n];steps = new int[n][n]; queue = new LinkedList<>(); bfs(A,2);
pw.println(ans - 1);pw.flush();
}
static class Pos{int y,x; public Pos(int y,int x){this.y = y; this.x = x;} }
static Queue<Pos> queue = new LinkedList<>(); static int[][] di = { {1,0} ,{ 0,1} ,{-1, 0} ,{0,-1} };
static void bfs(Pos A,int sta){
queue.add(A); steps[A.y][A.x] = 1; vis[A.y][A.x] = sta;
while(!queue.isEmpty()){
Pos cur = queue.poll(); int y = cur.y,x = cur.x,ny,nx; int step = steps[y][x];
// 匹配到B
if(map[y][x] == 'B'){
ans = Math.min(ans,step); return;
}
// 确定该点可以进入的状态 如果是A点,状态不改
if(cur != A){ //状态为 '-' 只能配置1'+'号 ,否则就是2'-'
vis[y][x] = map[y][x] == '-' ? 1 : 2;
}
for(int i = 0; i < 4; i++){
ny = y + di[i][0]; nx = x + di[i][1];
if(check(ny,nx,vis[y][x])){
queue.add(new Pos(ny,nx)); steps[ny][nx] = step + 1;
}
}
}
}
static boolean check(int y,int x,int sta){ //'0' 表示未访问 1表示 只能匹配'+' ,2 表示只能匹配'-'
char[] status = {0,'+','-' };
// 保证该点没有越界 保证该点状态对应 该点是'B 未访问过
return y >= 0 && y < n && x >= 0 && x < n && (map[y][x] == status[sta] || map[y][x] == 'B') && steps[y][x] == 0;
}
static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
static StreamTokenizer st = new StreamTokenizer(bf);
static int nextInt()throws Exception{st.nextToken(); return (int)st.nval;}
static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
}