計蒜客藍橋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;
	}

}


繼續加油~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章