分析:
1 字符不同,消不了
2 转折次数>2,消不了
这俩点进行剪枝
本题运用深搜,深搜原理点此
import java.util.Scanner;
public class Main{
static int n,m;
static Chess[][] chess;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
n=sc.nextInt();
m=sc.nextInt();
if(n==0&&m==0)
return;
chess=new Chess[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
chess[i][j]=new Chess(i, j, sc.nextInt());
}
}
int C=sc.nextInt();
for (int i = 0; i < C; i++) {
Chess state=chess[sc.nextInt()-1][sc.nextInt()-1];
num=state.c;
Chess end=chess[sc.nextInt()-1][sc.nextInt()-1];
if(state.c!=end.c||num==0){
System.out.println("NO");
continue;
}
for (int j = 0; j < n; j++) {
for (int j2 = 0; j2 < m; j2++) {
chess[j][j2].isVitis=false;
}
}
state.isVitis=true;
if(dfsChessOne(state,end))
System.out.println("YES");
else
System.out.println("NO");
}
}
}
static int[][] dir={{-1,0},{0,-1},{1,0},{0,1}};
static String[] direction={"N","W","S","E"};
static int num;
private static boolean dfsChessOne(Chess state, Chess end) {
for (int i = 0; i < dir.length; i++) {
int x=state.x+dir[i][0];
int y=state.y+dir[i][1];
if(x>=0&&x<n && y>=0&&y<m && (chess[x][y].c==0 ||chess[x][y].c==num)&& !chess[x][y].isVitis){
chess[x][y].direction=direction[i];
chess[x][y].isVitis=true;
if(dfsChess(chess[x][y], end,0))
return true;
chess[x][y].isVitis=false;
}
}
return false;
}
private static boolean dfsChess(Chess state, Chess end,int count) {
state.isVitis=true;
//转折数剪枝
if(count>2)
return false;
//发现
if(state.c==num){
if(state.x==end.x&&state.y==end.y)
return true;
else
return false;
}
for (int i = 0; i < dir.length; i++) {
int x=state.x+dir[i][0];
int y=state.y+dir[i][1];
int p=count;
if(x>=0&&x<n && y>=0&&y<m && (chess[x][y].c==0 ||chess[x][y].c==num)&& !chess[x][y].isVitis){
if(!direction[i].equals(state.direction))
count++;
chess[x][y].direction=direction[i];
if(dfsChess(chess[x][y], end,count))
return true;
chess[x][y].isVitis=false;
}
count=p;
}
return false;
}
static class Chess{
int x,y,c;
boolean isVitis;
String direction;
public Chess(int x, int y, int c) {
this.x = x;
this.y = y;
this.c = c;
isVitis = false;
direction=null;
}
}
}