04-穿越雷区
题目描述
已知的地图是一个方阵,上面用字母标出了A,B区,其它区都标了正号或负号分别表示正负能量辐射区。
例如:
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -
坦克车只能水平或垂直方向上移动到相邻的区。
数据格式要求:
输入第一行是一个整数n,表示方阵的大小, 4<=n<100
接下来是n行,每行有n个数据,可能是A,B,+,-中的某一个,中间用空格分开。
A,B都只出现一次。
要求输出一个整数,表示坦克从A区到B区的最少移动步数。
如果没有方案,则输出-1
例如:
用户输入:
5
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -
则程序应该输出:
10
资源约定:
峰值内存消耗 < 512M
CPU消耗 < 1000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入…” 的多余内容。
所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
注意: main函数需要返回0
注意: 只使用ANSI C/ANSI C++ 标准,不要调用依赖于编译环境或操作系统的特殊函数。
注意: 所有依赖的函数必须明确地在源文件中 #include , 不能通过工程
dfs题目,注意回溯时的细节
import java.util.Scanner;
public class code04_crossMines {
static int res = Integer.MAX_VALUE;
static int[][] dir = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
char[][] mines = new char[n][n];
int row = 0, col = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
mines[i][j] = sc.next().charAt(0);
if (mines[i][j]=='A') {
row = i;
col = j;
}
}
}
//记录是否被访问过
int[][] visited = new int[n][n];
countStep(mines, visited, row, col, 0);
System.out.println(res);
sc.close();
}
public static void countStep(char[][] mines, int[][] visited, int row, int col, int step) {
//到达B区 认为有一条路径 取最小值
if (mines[row][col]=='B') {
if (step < res) {
res = step;
}
return;
}
visited[row][col] = 1;
for (int i = 0; i < dir.length; i++) {
int nextRow = row + dir[i][0];
int nextCol = col + dir[i][1];
//判断是否越界
if (nextCol < 0 || nextRow < 0 || nextRow >= mines.length || nextCol >= mines.length) {
continue;
}
if (visited[nextRow][nextCol] == 0) {
visited[nextRow][nextCol] = 1;
//每次走的 能量区不能一样
if (mines[nextRow][nextCol]!=mines[row][col]) {
countStep(mines, visited, nextRow, nextCol, step + 1);
}
//回溯
visited[nextRow][nextCol] = 0;
}
}
}
}
运行结果