计蒜客蓝桥B组模拟赛五-F. 藏宝图

蒜头君得到一张藏宝图。藏宝图是一个 10 \times 1010×10 的方格地图,图上一共有 1010 个宝藏。有些方格地形太凶险,不能进入。

整个图只有一个地方可以出入,即是入口也是出口。蒜头君是一个贪心的人,他规划要获得所有宝藏以后才从出口离开。

藏宝图上从一个方格到相邻的上下左右的方格需要 11 天的时间,蒜头君从入口出发,找到所有宝藏以后,回到出口,最少需要多少天。

思路:

状压10个状态,然后bfs就行了,,

没想到到现在还会犯"<<和"-"优先级的错误,mdzz...

代码:

import java.util.HashMap;
import java.util.LinkedList;

public class Main6 {

	private static class Node implements Comparable<Node>{
		int x, y, t, vis;
		public Node(int x, int y, int t, int vis) {
			this.x = x;
			this.y = y;
			this.t = t;
			this.vis = vis;
		}
		@Override
		public int compareTo(Node o) {
			// TODO Auto-generated method stub
			return this.t - o.t;
		}
		
	}
	private static String[] mp = {"O......B..",
								  "...X..B...",
								  ".X..B..X..",
								  ".B...X..B.",
								  ".X..B.X...",
							  	  "..X....X..",
								  ".....X..B.",
								  ".X.X..B...",
								  ".B....XX..",
								  "..X..XB..."
								};
	private static int nex[][] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
	private static boolean[][][] vis = new boolean[1<<10][15][15];
	private static HashMap<Integer, Integer> map = new HashMap<>();
//	private static PriorityQueue<Node> q = new PriorityQueue<>();
	private static LinkedList<Node> q = new LinkedList<>();
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ids = 0;
		System.out.println(bfs());
	}
	
	private static int ids;
	private static int ID(int x, int y) {
		if(map.containsKey(x*10+y)) {
			return map.get(x*10+y);
		}
		map.put(x*10+y, ids);
		return ids++;
	}
	private static int bfs() {
		q.offer(new Node(0, 0, 0, 0));
		vis[0][0][0] = true;
		while(!q.isEmpty()) {
			Node top = q.poll();
			if(top.vis == ((1<<10)-1) && top.x == 0 && top.y == 0) {
				return top.t;
			}
			for(int i = 0; i < 4; ++i) {
				int tx = top.x + nex[i][0];
				int ty = top.y + nex[i][1];
				if(tx < 0 || tx >= 10 || ty < 0 || ty >= 10) {
					continue;
				}
				if(mp[tx].charAt(ty) == 'X') {
					continue;
				}
				if(vis[top.vis][tx][ty]) {
					continue;
				}
				int tmp = top.vis;
				if(mp[tx].charAt(ty) == 'B') {
					int id = ID(tx, ty);
					if((top.vis & (1<<id)) == 0) {
						tmp += (1<<id);
					}
				}
				q.offer(new Node(tx, ty, top.t+1, tmp));
				vis[tmp][tx][ty] = true;
			}
		}
		return -1;
	}

}


继续加油~

猜你喜欢

转载自blog.csdn.net/yo_bc/article/details/79761218