迷宫寻路

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;
		}
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值