题目还有分析过程都在注释里了
public class LianTongCheck {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
sc.nextLine();
char[][] graph=new char[N][N];
for(int i=0;i<N;i++)
graph[i]=sc.nextLine().toCharArray();
int M=sc.nextInt();
int[][] request=new int[M][4];
for(int i=0;i<M;i++)
for(int j=0;j<4;j++)
request[i][j]=sc.nextInt();
for(int i=0;i<M;i++)
{
boolean ok=check(graph,new int[N][N],request[i]);
System.out.println(ok);
}
}
private static boolean check(char[][] graph, int[][] label, int[] points) {
int x1=points[0];
int y1=points[1];
int x2=points[2];
int y2=points[3];
if(x1==x2&&y1==y2)
return true;
int value=graph[x1][y1];
boolean f1=false;
boolean f2=false;
boolean f3=false;
boolean f4=false;
if(x1-1>=0&&label[x1-1][y1]==0&&graph[x1-1][y1]==value)
{
label[x1-1][y1]=1;
points[0]=x1-1;
f1=check(graph,label,points);
label[x1-1][y1]=0;
points[0]=x1;
}
if(x1+1<graph.length&&label[x1+1][y1]==0&&graph[x1+1][y1]==value)
{
label[x1+1][y1]=1;
points[0]=x1+1;
f2=check(graph,label,points);
label[x1+1][y1]=0;
points[0]=x1;
}
if(y1-1>=0&&label[x1][y1-1]==0&&graph[x1][y1-1]==value)
{
label[x1][y1-1]=1;
points[1]=y1-1;
f3=check(graph,label,points);
label[x1][y1-1]=0;
points[1]=y1;
}
if(y1+1<graph.length&&label[x1][y1+1]==0&&graph[x1][y1+1]==value)
{
label[x1][y1+1]=1;
points[1]=y1+1;
f4=check(graph,label,points);
label[x1][y1+1]=0;
points[1]=y1;
}
return f1||f2||f3||f4;
}
}