- 见过很多次了,向不同方向搜索。
- code:
import java.util.Scanner;
public class Main {
private static int step = 10000000;
private static int dir[][] = new int[][] {{-1,0},{0,1},{1,0},{0,-1}};
private static char[][] c = new char[101][101];
private static boolean[][] vis = new boolean[101][101];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
int n = Integer.parseInt(sc.nextLine());
int sx = 0, sy = 0, ex = 0, ey = 0;
for(int i = 0;i<n;i++) {
String s = sc.nextLine();
for(int j = 0;j<n;j++) {
c[i][j] = s.charAt(j*2);
if(c[i][j] == 'A') {
sx = i;
sy = j;
}
if(c[i][j] == 'B') {
ex = i;
ey = j;
}
}
}
vis[sx][sy] = true;
dfs(sx, sy, 0, n, ex, ey, 'A');
if(step == 10000000)
System.out.println(-1);
else
System.out.println(step);
}
sc.close();
}
public static void dfs(int x, int y, int t, int n, int ex, int ey, char ch) {
if(x<0 || x>n || y<0 || y>n)
return;
if(x==ex && y==ey) {
if(t<step)
step=t;
return;
}
for(int k = 0;k<4;k++) {
int px = x + dir[k][0], py = y + dir[k][1];
if(px > n || px < 0 || py > n || py < 0)
continue;
if(!vis[px][py] && c[px][py]!=ch) {
vis[px][py] = true;
dfs(px,py,t+1,n, ex, ey, c[px][py]);
vis[px][py] = false;
}
}
}
}