AcWing1101. 献给阿尔吉侬的花束
2021-02-03
AcWing1101. 献给阿尔吉侬的花束
题意:
经典的走迷宫问题,给定一个二维字符矩阵,S代表开始,E代表终点,问是否能走到并且输出最小步数
思路
直接bfs即可
代码
思路:简单的迷宫问题,bfs解决即可,我在处理的时候遇到以下问题:
1. 习惯用了c++,便想这开双层pair丢进队列搜索即可,但是java的pair好像没有在unit包下,于是尝试用了map
2. 使用map时采用了双层map套的形式,但是在clear的时候,会将map彻底的清空,我们都知道java的机制中变量名更形象
来说是一种引用,好奇怪我将map清空的时候java虚拟机就将次地址擦除的导致队列中之前丢进去的坐标也会消失,最后
是成功AC了学到了2333
import java.util.*;
public class Main {
public static int bfs(String []s, int n,int m){
int []dx={-1,0,1,0};
int []dy={0,-1,0,1};
int [][]vis=new int[210][210];
int x = 0,y=0;
Map<Integer,Integer> mp = new HashMap<>();
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
if(s[i].charAt(j)=='S') {
x=i;
y=j;
break;
}
}
}
Queue<Map<Integer,Map<Integer,Integer>>> q=new ArrayDeque<>();
Map<Integer,Integer>p=new HashMap<>();
p.put(x,y);
Map <Integer,Map<Integer,Integer>> pair=new HashMap<>();
pair.put(1,p);
q.add(pair);
while(q.size()>=1) {
pair=q.poll();
// System.out.println(pair);
int cnt = 0;
for(Map.Entry<Integer,Map<Integer,Integer>> pp:pair.entrySet()) {
cnt=pp.getKey();
p=pp.getValue();
for(Map.Entry<Integer,Integer>ppp:p.entrySet()) {
x=ppp.getKey();
y=ppp.getValue();
}
}
if(s[x].charAt(y)=='E') {
return cnt-1;
}
for(int i=0;i<4;i++) {
int fx=x+dx[i];
int fy=y+dy[i];
if(fx<1||fx>n||fy<1||fy>m||vis[fx][fy]==1||s[fx].charAt(fy)=='#')
continue;
vis[fx][fy]=1;
p=new HashMap<>();
p.put(fx,fy);
pair=new HashMap<>();
pair.put(cnt+1,p);
q.add(pair);
}
}
return -1;
}
public static void main(String[] args) {
int T;
Scanner sc=new Scanner(System.in);
T=sc.nextInt();
for(int k=1;k<=T;k++){
String []s=new String[210];
int n,m;
n=sc.nextInt();
m=sc.nextInt();
for(int i=1;i<=n;i++) {
s[i]=sc.next();
s[i]=" "+s[i];
}
int x=bfs(s,n,m);
if(x==-1) System.out.println("oop!");
else System.out.println(x);
}
}
}