DFS
import java.io.*;
import java.util.*;
class Main{
static int N = 110, row, col;
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static char[][] a = new char[N][N];
static int[][] dir = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
public static void main(String[] args) throws Exception{
int t = Integer.valueOf(read.readLine());
while(t-- > 0){
int n = Integer.valueOf(read.readLine());
row = col = n;
for(int i = 0; i < n; i++){
String s = read.readLine();
for(int j = 0; j < n; j++){
a[i][j] = s.charAt(j);
}
}
String[] ss = read.readLine().split(" ");
int x1 = Integer.valueOf(ss[0]);
int y1 = Integer.valueOf(ss[1]);
int x2 = Integer.valueOf(ss[2]);
int y2 = Integer.valueOf(ss[3]);
boolean[][] st = new boolean[n][n];
if(a[x1][y1] == '#' || a[x2][y2] == '#'){
System.out.println("NO");
}else if(x1 == x2 && y1 == y2){
System.out.println("YES");
}else if(dfs(x1, y1, x2, y2, st)){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
public static boolean dfs(int x1, int y1, int x2, int y2, boolean[][] st){
for(int i = 0; i < 4; i++){
int nx = x1 + dir[i][0];
int ny = y1 + dir[i][1];
if(nx < 0 || nx >= row || ny < 0 || ny >= col) continue;
if(st[nx][ny] || a[nx][ny] == '#') continue;
st[nx][ny] = true;
if(nx == x2 && ny == y2) return true;
if(dfs(nx, ny, x2, y2, st)) return true;
}
return false;
}
}
BFS
import java.io.*;
import java.util.*;
class Main{
static int N = 110, row, col;
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static char[][] a = new char[N][N];
static int[][] dir = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
public static void main(String[] args) throws Exception{
int t = Integer.valueOf(read.readLine());
while(t-- > 0){
int n = Integer.valueOf(read.readLine());
row = col = n;
for(int i = 0; i < n; i++){
String s = read.readLine();
for(int j = 0; j < n; j++){
a[i][j] = s.charAt(j);
}
}
String[] ss = read.readLine().split(" ");
int x1 = Integer.valueOf(ss[0]);
int y1 = Integer.valueOf(ss[1]);
int x2 = Integer.valueOf(ss[2]);
int y2 = Integer.valueOf(ss[3]);
if(bfs(x1, y1, x2, y2)) System.out.println("YES");
else System.out.println("NO");
}
}
public static boolean bfs(int x1, int y1, int x2, int y2){
Queue<int[]> q = new LinkedList();
if(a[x1][y1] == '#' || a[x2][y2] == '#') return false;
if(x1 == x2 && y1 == y2) return true;
q.offer(new int[]{x1, y1});
boolean[][] st = new boolean[row][col];
st[x1][y1] = true;
while(!q.isEmpty()){
int[] poll = q.poll();
for(int i = 0; i < 4; i++){
int nx = dir[i][0] + poll[0];
int ny = dir[i][1] + poll[1];
if(nx < 0 || nx >= row || ny < 0 || ny >= col) continue;
if(st[nx][ny] || a[nx][ny] == '#') continue;
st[nx][ny] = true;
if(nx == x2 && ny == y2) return true;
q.offer(new int[]{nx, ny});
}
}
return false;
}
}
赞一个!