

样例输入1
7 8
#@#####@
#@a#@@r@
#@@#x@@@
@@#@@#@#
#@@@##@@
@#@@@@@@
@@@@@@@@
样例输出1
13
样例输入2
13 40
@x@@##x@#x@x#xxxx##@#x@x@@#x#@#x#@@x@#@x
xx###x@x#@@##xx@@@#@x@@#x@xxx@@#x@#x@@x@
#@x#@x#x#@@##@@x#@xx#xxx@@x##@@@#@x@@x@x
@##x@@@x#xx#@@#xxxx#@@x@x@#@x@@@x@#@#x@#
@#xxxxx##@@x##x@xxx@@#x@x####@@@x#x##@#@
#xxx#@#x##xxxx@@#xx@@@x@xxx#@#xxx@x#####
#x@xxxx#@x@@@@##@x#xx#xxx@#xx#@#####x#@x
xx##@#@x##x##x#@x#@a#xx@##@#@##xx@#@@x@x
x#x#@x@#x#@##@xrx@x#xxxx@##x##xx#@#x@xx@
#x@@#@###x##x@x#@@#@@x@x@@xx@@@@##@@x@@x
x#xx@x###@xxx#@#x#@@###@#@##@x#@x@#@@#@@
#@#x@x#x#x###@x@@xxx####x@x##@x####xx#@x
#x#@x#x######@@#x@#xxxx#xx@@@#xx#x#####@
样例输出2
7
思路:刚开始我对‘x’与‘@’处理的区别就是一个的深度多加1,测试后只能通过几组数据,其实我忽略一个问题就是:这样做出来的最短路径未必花费最短时间,比如:
@@@@@
rxxxxa
这个的最短路径需要花费7个单位时间,而显然我们只需花费6个单位时间就可以拯救公主。
还是需要借助数据结构优先队列解决。
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main{
static int [] dx = {-1,0,0,1};
static int [] dy = {0,-1,1,0};
static int step = 1;
static boolean flag = false;
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
sc.nextLine();
char [][]graph = new char[n][];
int [][]vis = new int[n][m];
for(int i=0;i<n;i++){
graph[i] = sc.nextLine().toCharArray();
}
//创建队列
PriorityQueue<Node> queue = new PriorityQueue<>();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(graph[i][j] == 'r') queue.add(new Node(i,j,0));
}
}
while(!queue.isEmpty()){
Node poll = queue.poll();
int x = poll.i;
int y = poll.j;
int deep = poll.depth;
vis[x][y] = 1;
if(graph[x][y] == 'a'){
flag = true;
step = poll.depth;
break;
}
for(int u=0;u<4;u++){
int tx = x+dx[u] , ty = y+dy[u];
if(tx >=0 && tx < n && ty>=0 && ty<m && graph[tx][ty] != '#' && vis[tx][ty] == 0){
vis[tx][ty] = 1;
if(graph[tx][ty] == 'x') queue.add(new Node(tx,ty,deep+2));
else queue.add(new Node(tx,ty,deep+1));
}
}
}
if(flag == true) System.out.print(step);
else System.out.print("Impossible");
}
//将坐标与深度封装为一个类,并实现比较接口Comparable
static class Node implements Comparable<Node>{
int i;
int j;
int depth;
public Node(int i,int j,int depth){
this.i = i;
this.j = j;
this.depth = depth;
}
//按照点的深度从小到大排序
public int compareTo(Node o) {
int x = this.depth - o.depth;
if(x == 0) return this.depth - o.depth;
else return x;
}
}
}
本文介绍了如何通过结合广度优先搜索(BFS)和优先队列来解决‘拯救行动’问题。初始方法仅考虑路径长度,但忽略了时间成本。通过优先队列可以找到花费时间最短的最短路径,例如在@example中,用7个单位时间的路径实际上可以缩短到6个单位时间。
1万+

被折叠的 条评论
为什么被折叠?



