import java.util.LinkedList;
import java.util.Scanner;
public class Main {
// 四个方向
private static int [] x = new int [] {0, 0, 1, -1};
private static int [] y = new int [] {1, -1, 0, 0};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
int M = sc.nextInt();
int N = sc.nextInt();
sc.nextLine();
char[][] ch = new char[M][N];
for(int i = 0; i < M; i++) {
ch[i] = sc.nextLine().toCharArray();
}
int x0 = 0, y0 = 0;
int xd = 0, yd = 0;
for(int i = 0; i < M; i++) {
for(int j = 0; j < M; j++) {
if(ch[i][j] == '2') {
x0 = i;
y0 = j;
continue;
}
if(ch[i][j] == '3') {
xd = i;
yd = j;
break;
}
}
}
System.out.println(BFS(ch,M,N,x0,y0,xd,yd));
}
}
private static int BFS (char[][] ch, int M, int N, int x0, int y0, int xd, int yd) {
LinkedList<Node> queue = new LinkedList<>();
int[][][] keys = new int[M][N][1024];
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
for(int k = 0; k < 1024; k++) {
keys [i][j][k] = Integer.MAX_VALUE;
}
}
}
queue.add(new Node(x0, y0, 0));
keys[x0][y0][0] = 0;
Node node = null;
int a = 0;
int b = 0;
int key = 0;
while(queue.size() > 0) {
node = queue.poll();
a = node.a;
b = node.b;
key = node.key;
if(a == xd && b == yd ) {
return keys[a][b][key];
}
for(int i = 0; i < 4; i++) {
a = node.a + x[i];
b = node.b + y[i];
key = node.key;
if(!isValid(a, b, M, N, ch))
continue;
//最多10把钥匙
if (ch[a][b] >='a' && ch[a][b] <= 'j') {
key = key | (0x1 << (ch[a][b] - 'a'));
}
// 有对应钥匙往下走,没有则跳过
if(ch[a][b] >= 'A' && ch[a][b] <= 'J') {
if((key & (0x1 << (ch[a][b] - 'A'))) > 0){
// key = key | ~(0x1 <<(ch[x][y] - 'A'));
}
else {
continue;
}
}
if(keys[a][b][key] > keys[node.a][node.b][node.key] + 1) {
keys[a][b][key] = keys[node.a][node.b][node.key] + 1;
queue.add(new Node(a,b,key));
}
}
}
return Integer.MAX_VALUE;
}
private static boolean isValid(int a, int b, int M, int N, char[][] chs) {
if(a >= 0 && a < M && b >= 0 && b < N && chs[a][b] != '0')
return true;
return false;
}
private static class Node{
int a;
int b;
int key;
public Node(int a, int b, int keys) {
this.a = a;
this.b = b;
this.key = keys;
}
}
}
迷宫寻路
最新推荐文章于 2021-03-27 10:53:46 发布