1、问题描述
小明在玩一款迷宫游戏,在游戏中他要控制自己的角色离开一间由NxN个格子组成的2D迷宫。
小明的起始位置在左上角,他需要到达右下角的格子才能离开迷宫。
每一步,他可以移动到上下左右相邻的格子中(前提是目标格子可以经过)。
迷宫中有些格子小明可以经过,我们用'.'表示;
有些格子是墙壁,小明不能经过,我们用'#'表示。
此外,有些格子上有陷阱,我们用'X'表示。除非小明处于无敌状态,否则不能经过。
有些格子上有无敌道具,我们用'%'表示。
当小明第一次到达该格子时,自动获得无敌状态,无敌状态会持续K步。
之后如果再次到达该格子不会获得无敌状态了。
处于无敌状态时,可以经过有陷阱的格子,但是不会拆除/毁坏陷阱,即陷阱仍会阻止没有无敌状态的角色经过。
给定迷宫,请你计算小明最少经过几步可以离开迷宫输入格式
----
第一行包含两个整数N和K。 (1 <= N <= 1000 1 <= K <= 10)
以下N行包含一个NxN的矩阵。
矩阵保证左上角和右下角是'.'。输出格式
----
一个整数表示答案。如果小明不能离开迷宫,输出-1。样例输入
5 3
...XX
##%#.
...#.
.###.
.....样例输出
10
样例输入
5 1
...XX
##%#.
...#.
.###.
.....样例输出
12
2、代码实现
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class 迷宫与陷阱 {
static int n;
static int k;
static char[][] map;
static int[] xs = {1,0,-1,0};
static int[] ys = {0,1,0,-1};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
k = scanner.nextInt();
map = new char[n][n];
for(int i = 0;i < n;i++) {
map[i] = scanner.next().toCharArray();
}
bfs();
}
public static void bfs() {
Queue<Vertex> queue = new LinkedList<>();
boolean[][][] visit = new boolean[n][n][k + 1];
queue.offer(new Vertex(0,0,0,0));
visit[0][0][0] = true;
while(!queue.isEmpty()) {
Vertex vertex = queue.poll();
if(vertex.x == n - 1 && vertex.y == n - 1) {
System.out.println(vertex.step);
return;
}
for(int i = 0;i < 4;i++) {
int x = vertex.x + xs[i];
int y = vertex.y + ys[i];
int z = vertex.invincible;
//判断边界和墙
if(x < 0 || x >= n || y < 0 || y >= n || map[x][y] == '#' || (map[x][y] == 'X' && z == 0) || visit[x][y][z]) {
continue;
}
if(map[x][y] == 'X') {
if(z > 0) {
queue.offer(new Vertex(x,y,vertex.step + 1,z - 1));
visit[x][y][z] = true;
}
}else if(map[x][y] == '%') {
queue.offer(new Vertex(x,y,vertex.step + 1,k));
visit[x][y][z] = true;
map[x][y] = '.';
}else {
queue.offer(new Vertex(x,y,vertex.step + 1,z > 0 ? z - 1 : 0));
visit[x][y][z] = true;
}
}
}
}
}
class Vertex{
int x;
int y;
int step;
int invincible;
public Vertex(int x, int y, int step, int invincible) {
super();
this.x = x;
this.y = y;
this.step = step;
this.invincible = invincible;
}
}