迷宫寻路（BFS、Java实现）

5 5
02111
01a0A
01003
01001
01111

7

题解

(key&(1<<(ch-‘a’))==1表示key有a的钥匙。

代码

import java.io.*;
import java.math.*;
import java.util.*;

public class Main{
static class node {
int x,y,key,sum;
public node(int x,int y,int key,int sum) {
this.x=x;
this.y=y;
this.key=key;
this.sum=sum;
}
}

public static String []g=new String[107];
public static int N,M;

public static void main(String[] args){
Scanner in=new Scanner(System.in);
N=in.nextInt();
M=in.nextInt();
for(int i=0;i<N;i++){
g[i]=in.next();
}
int u=-1,v=0;
for(int i=0;i<N;i++) {
String tmp=g[i];
for(int j=0;j<tmp.length();j++) {
if(tmp.charAt(j)=='2') {
u=i;
v=j;
break;
}
}
if(u!=-1) break;
}
System.out.println(bfs(u,v));
}

private static int bfs(int u,int v){
int [][]dir={{0,1},{0,-1},{-1,0},{1,0}};
int [][][]vis=new int[107][107][1025];
node tmp=new node(u,v,0,0);
que.offer(tmp);
vis[u][v][0]=1;

while(!que.isEmpty()) {
tmp=que.poll();
int x=tmp.x;
int y=tmp.y;
int key=tmp.key;
int sum=tmp.sum;
if(g[x].charAt(y)=='3') return sum;

for(int i=0;i<4;i++) {
int fx=x+dir[i][0];
int fy=y+dir[i][1];

if(fx<0 || fx>=N || fy<0 || fy>=M) continue;
char ch=g[fx].charAt(fy);
if(ch=='0') continue;
if(ch>='A' && ch<='Z') {
if((key&(1<<(ch-'A')))==0) {
continue;
}
}
int now=0;
if(g[fx].charAt(fy)<='z' && g[fx].charAt(fy)>='a') {
now=1<<(g[fx].charAt(fy)-'a');
}
if(vis[fx][fy][key|now]==0) {
vis[fx][fy][key|now]=1;
que.offer(new node(fx,fy,key|now,sum+1));
}

}
}
return -1;
}
}

04-09 1155
08-25 2355

03-08 25
08-30 197
01-28 494
05-17 995
10-08
05-16 2477
03-17 9974