藏宝图
蒜头君得到一张藏宝图。藏宝图是一个 10×1010 \times 1010×10 的方格地图,图上一共有 101010 个宝藏。有些方格地形太凶险,不能进入。
整个图只有一个地方可以出入,即是入口也是出口。蒜头君是一个贪心的人,他规划要获得所有宝藏以后才从出口离开。
藏宝图上从一个方格到相邻的上下左右的方格需要 111 天的时间,蒜头君从入口出发,找到所有宝藏以后,回到出口,最少需要多少天。
每个点状态用 d[x][y][state]表示,state表示每个宝藏是否获取的状态压缩。然后BFS即可。
我们将每个宝藏进行编号
"...X..0...",
".X..8..X..",
".7...X..6.",
".X..5.X...",
"..X....X..",
".....X..3.",
".X.X..1...",
".4....XX..",
"..X..X2...",
我们标记宝藏从0-9其实是很巧妙的,一个原因是10会占两个字符的位置不可以用1-10编号会改变地图
其次我们保存最终答案的数组是int d[11][11][1<<10];
最后一个维度记录状态也就是用二进制状态压缩后第十个位置时1即1000000000(二进制)而对于数组而言
这是一个十进制数且下标从0开始0~(1<<10)-1,所以我们以下标为0时的数组表示了第一个宝藏的有无状态
也就是移0位,最后输出(1<<10)-1处的数组即可也就是九个1,111111111,表示全部宝藏都有了
code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
char mat[11][11]={ //藏宝图
"s......9..",
"...X..0...",
".X..8..X..",
".7...X..6.",
".X..5.X...",
"..X....X..",
".....X..3.",
".X.X..1...",
".4....XX..",
"..X..X2...",
};
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};//方向
struct node{
int x;//横坐标
int y;//纵坐标
int s;//状态
node(int xx,int yy,int ss):x(xx),y(yy),s(ss){}
};
int d[11][11][1<<10];//d[X][Y][S]代表到达xy位置时,状态为s(即收集了确定的若干个宝藏时)的最少步数
int in(int x,int y){
return (x >= 0 && x < 10 && y >= 0 && y < 10 && mat[x][y] != 'X');
}
void bfs(){
int i;
int x,y,s;
int tx,ty,ts;
queue<node> q;
memset(d,-1,sizeof(d));
q.push(node(0,0,0));
d[0][0][0] = 0;
while(!q.empty()){
x = q.front().x;
y = q.front().y;
s = q.front().s;
q.pop();
for(i = 0; i < 4; i++){
tx = x + dir[i][0];
ty = y + dir[i][1];
ts = s;
if(in(tx,ty)){
if(mat[tx][ty] >= '0' && mat[tx][ty] <= '9')
ts = s | (1<<(mat[tx][ty]-'0'));
if(d[tx][ty][ts] == -1){
d[tx][ty][ts] = d[x][y][s] + 1;
q.push(node(tx,ty,ts));
}
}
}
}
}
int main(){
bfs();
cout << d[0][0][(1<<10)-1] << endl;//下标从0开始所以当所有宝藏收集后对应的数组下标应该为(1<<10)-1
return 0;
}