迷失之牙
样例输入:
5 6
1 1 0 0 0 1
1 0 1 0 0 1
0 1 0 1 0 0
1 1 1 0 0 1
1 1 1 1 1 1
3
0 0
4 5
2
0 0
4 5
3
3 5
3 0
0
样例输出:
true
false
true
ac代码(附注释):
package 迷失之牙;
import java.util.Scanner;
public class Main {
Scanner sc = new Scanner(System.in);
int n = 0;
int m = 0;
// 终点(end)坐标
int ex = 0;
int ey = 0;
int[][] map; //迷宫数组
boolean canSolve;
public Main() {
n = sc.nextInt();
m = sc.nextInt();
map = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = sc.nextInt();
}
}
while(sc.hasNext()) {
int p = sc.nextInt(); //power能量
if(p==0) break;
canSolve = false;
// 起点(start)坐标
int sx = sc.nextInt();
int sy = sc.nextInt();
ex = sc.nextInt();
ey = sc.nextInt();
enterMaze(sx, sy, p);
if (canSolve) {
System.out.println(true);
} else {
System.out.println(false);
}
}
}
public static void main(String[] args) {
new Main();
}
void enterMaze(int x, int y, int energy) {
if (energy < 0 || x < 0 || y < 0 || x >= n || y >= m || map[x][y] == -1) {
return;
} else {
int temp = map[x][y]; // 局部变量!!!
map[x][y] = -1; //起点以及走过的位置标记为-1
if (x == ex && y == ey) {
map[x][y] = temp; // 测试多组数据 结果为true或者false都要将标记为-1的位置的能量赋值回去
canSolve = true;
return;
}
// 向上
if(x-1>=0)
enterMaze(x - 1, y, energy - map[x-1][y]);
// 向右
if(y + 1<m)
enterMaze(x, y + 1, energy - map[x][y+1]);
// 向下
if(x+1<n)
enterMaze(x + 1, y, energy - map[x+1][y]);
// 向左
if(y-1>=0)
enterMaze(x, y - 1, energy - map[x][y-1]);
map[x][y] = temp;
}
}
}