X星的坦克战车很奇怪,它必须交替地穿越正能量辐射区和负能量辐射区才能保持正常运转,否则将报废。
某坦克需要从A区到B区去(A,B区本身是安全区,没有正能量或负能量特征),怎样走才能路径最短?
已知的地图是一个方阵,上面用字母标出了A,B区,其它区都标了正号或负号分别表示正负能量辐射区。
例如:
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -
坦克车只能水平或垂直方向上移动到相邻的区。
数据格式要求:
输入第一行是一个整数n,表示方阵的大小, 4<=n<100
接下来是n行,每行有n个数据,可能是A,B,+,-中的某一个,中间用空格分开。
A,B都只出现一次。
要求输出一个整数,表示坦克从A区到B区的最少移动步数。
如果没有方案,则输出-1
例如:
用户输入:
5
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -
则程序应该输出:
10
资源约定:
峰值内存消耗(含虚拟机) < 512M
CPU消耗 < 2000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入…” 的多余内容。
所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
注意:不要使用package语句。不要使用jdk1.7及以上版本的特性。
注意:主类的名字必须是:Main,否则按无效代码处理。
import java.util.Scanner;
public class BB010102 {
private static char[][] map = new char[6][6];
private static int step = 1000;
private static int n;
private static int[][] visit = new int[6][6];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int xA, yA;
n = scan.nextInt();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
map[i][j] = scan.next().charAt(0);
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
visit[i][j] = 0;
}
}
visit[1][1] = 1;
dfs(0, 1, 1);
System.out.println(step);
}
public static void dfs(int cur, int x, int y) {
int next[][] = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
int tx, ty, k;
if (map[x][y] == 'B') {
if (cur < step) {
step = cur;
if(step==10){
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(visit[i][j]);
}
System.out.println();
}
}
}
return;
}
for (k = 0; k <= 3; k++) {
// 计算下一个点的坐标
tx = x + next[k][0];
ty = y + next[k][1];
// 判断是否越界
if (tx < 1 || tx > n || ty < 1 || ty > n)
continue;
// 判断该点是否满足正负交替
if ( map[x][y]!= map[tx][ty] && visit[tx][ty] == 0) {
visit[tx][ty] = 1;
dfs(cur + 1, tx, ty);
visit[tx][ty] = 0;
}
}
return;
}
}