自己另辟蹊径想的新思路 果然好像还是不太行呀
java
import java.util.Scanner;
public class Main {
static int T;//样例组数
static int n;//矩阵大小
static int[] X = {0,1,0,-1};
static int[] Y = {1,0,-1,0};
static int[] X1 = {1,0,-1,0};
static int[] Y1 = {0,-1,0,1};
static int flag = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
T = scan.nextInt();
while((T--)>0)
{
n = scan.nextInt();
char[][] arr = new char[n][n];
int[][] vis = new int[n][n];
for(int i = 0;i<n;i++)
{
arr[i] =scan.next().toCharArray();
}
if(!dfs(0,0,vis,arr,n))//第一次就不通
{
System.out.println(0);
}
else
{
dfs1(0,0,vis,arr,n);//第二次标记
int[][] vis1 = new int[n][n];
if(dfs(0,0,vis1,arr,n))
{
System.out.println(2);
}
else
{
System.out.println(1);
}
}
}
}
static boolean dfs(int x,int y,int[][] vis,char[][] arr,int n)
{
if(arr[x][y] == 'C') return true;
if(arr[x][y]!='A') vis[x][y] = 1;
for(int i = 0;i<4;i++)
{
int x1 = x + X[i];
int y1 = y + Y[i];
if(x1>=0&&x1<n&&y1>=0&&y1<n&&vis[x1][y1]==0&&arr[x1][y1]!='X')
{
if(dfs(x1,y1,vis,arr,n)) return true;
}
}
return false;
}
static boolean dfs1(int x,int y,int[][] vis,char[][] arr,int n)
{
if(arr[x][y] == 'C' ) return true;
if(arr[x][y]!='A') vis[x][y] = 2;
for(int i = 0;i<4;i++)
{
int x1 = x + X1[i];
int y1 = y + Y1[i];
if(x1>=0&&x1<n&&y1>=0&&y1<n&&vis[x1][y1]==1&&arr[x1][y1]!='X')
{
arr[x1][y1] = 'X';
return true;
}
if(x1>=0&&x1<n&&y1>=0&&y1<n&&vis[x1][y1]!=2&&arr[x1][y1]!='X')
{
if(dfs1(x1,y1,vis,arr,n)) return true;
}
}
return false;
}
}