机器人走迷宫
标题:机器人走迷宫 | 时间限制:1秒 | 内存限制:65536K | 语言限制:不限
1、 房间由X*Y的方格组成,例如下图为6*4的大小。每一个方格以坐标(x,y)描述。
2、 机器人固定从方格(0,0)出发,只能向东或者向北前进。出口固定为房间的最东北角,如下图的方格(5,3)。用例保证机器人可以从入口走到出口。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int xNum = scanner.nextInt();
int yNum = scanner.nextInt();
int[][] map = new int[xNum][yNum];
int n = scanner.nextInt();
while (n > 0) {
int wallX = scanner.nextInt();
int wallY = scanner.nextInt();
map[wallX][wallY] = 1;
n--;
}
path(map, 0, 0, xNum - 1, yNum - 1);
int trap = 0;
int unReachable = 0;
for (int i = 0; i < xNum; i++) {
for (int j = 0; j < yNum; j++) {
if (map[i][j] == 2) {
trap++;
}
if (map[i][j] == 0) {
unReachable++;
}
}
}
System.out.println(trap + " " + unReachable);
}
public static void path(int[][] room, int nextStepX, int nextStepY, int x, int y) {
if (room[nextStepX][nextStepY] == 1) {
return;
}
if (room[nextStepX][nextStepY] != 0) {
return;
}
if (nextStepX == x && nextStepY == y) {
room[nextStepX][nextStepY] = -1;
return;
}
if (nextStepX < x) {
path(room, nextStepX + 1, nextStepY, x, y);
}
if (nextStepY < y) {
path(room, nextStepX, nextStepY + 1, x, y);
}
if (nextStepX == x || nextStepY == y) {
if (nextStepX == x && nextStepY < y && room[nextStepX][nextStepY + 1] != -1) {
room[nextStepX][nextStepY] = 2;
} else if (nextStepY == y && nextStepX < x && room[nextStepX + 1][nextStepY] != -1) {
room[nextStepX][nextStepY] = 2;
} else {
room[nextStepX][nextStepY] = -1;
}
} else if (room[nextStepX + 1][nextStepY] != -1 && room[nextStepX][nextStepY + 1] != -1) {
room[nextStepX][nextStepY] = 2;
} else {
room[nextStepX][nextStepY] = -1;
}
}
}
