目录
题目描述
小明在玩一款迷宫游戏,在游戏中他要控制自己的角色离开一间由 N×N 个格子组成的 2D 迷宫。
小明的起始位置在左上角,他需要到达右下角的格子才能离开迷宫。
每一步,他可以移动到上下左右相邻的格子中(前提是目标格子可以经过)。
迷宫中有些格子小明可以经过,我们用 '.' 表示。
有些格子是墙壁,小明不能经过,我们用 '#' 表示。
此外,有些格子上有陷阱,我们用 'X' 表示。除非小明处于无敌状态,否则不能经过。
有些格子上有无敌道具,我们用 '%' 表示。
当小明第一次到达该格子时,自动获得无敌状态,无敌状态会持续 K 步。
之后如果再次到达该格子不会获得无敌状态了。
处于无敌状态时,可以经过有陷阱的格子,但是不会拆除/毁坏陷阱,即陷阱仍会阻止没有无敌状态的角色经过。
给定迷宫,请你计算小明最少经过几步可以离开迷宫?
输入描述
输入描述
第一行包含两个整数 N,K (1≤N≤1000,1≤K≤10)。
以下 N 行包含一个 N×N 的矩阵。
矩阵保证左上角和右下角是 '.'。
输出描述
一个整数表示答案。如果小明不能离开迷宫,输出 -1。
输入输出样例
示例
输入
5 3
...XX
##%#.
...#.
.###.
.....
输出
10
运行限制
- 最大运行时间:3s
- 最大运行内存: 256M
原题链接
迷宫与陷阱https://www.lanqiao.cn/problems/229/learning/?page=1&first_category_id=1&problem_id=229
代码思路
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Exercise_09 {
static int xy[][] = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };
static char ca[][];
static int N;
static int K;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
N = scanner.nextInt();
K = scanner.nextInt();
ca = new char[N][N];
for (int i = 0; i < N; i++) {
ca[i] = scanner.next().toCharArray();
}
bfs();
}
static void bfs() {
Queue<Node> queue = new LinkedList<Node>();
queue.add(new Node(0, 0));
ca[0][0] = 'X';
int order = 0;
while (!queue.isEmpty()) {
int size = queue.size();
while (size-- > 0) {
Node temp = queue.poll();
int tempx = temp.x;
int tempy = temp.y;
int tempk = temp.k;
if (tempx == N - 1 && tempy == N - 1) {
System.out.println(order);
return;
}
for (int i = 0; i < xy.length; i++) {
int x = tempx + xy[i][0];
int y = tempy + xy[i][1];
if (x >= 0 && x < N && y >= 0 && y < N && ca[x][y] != '#') {
if (ca[x][y] == '%') {
ca[x][y] = 'X';
queue.add(new Node(x, y, K));
} else if (ca[x][y] == 'X') {
if (tempk > 0) {
queue.add(new Node(x, y, tempk - 1));
}
} else {
ca[x][y] = 'X';
if (tempk > 0) {
queue.add(new Node(x, y, tempk - 1));
} else {
queue.add(new Node(x, y));
}
}
}
}
}
order++;
}
System.out.println(-1);
}
}
class Node {
int x;
int y;
int k;
public Node(int x, int y) {
super();
this.x = x;
this.y = y;
}
public Node(int x, int y, int k) {
super();
this.x = x;
this.y = y;
this.k = k;
}
}