就是一道简单的BFS,由于要拿到所有宝藏,那么我们可以状态压缩宝藏集合, 为了使得状态表示完整,就需要在状态数组d中多增加一维。比较常见的题型。
细节参见代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const int INF = 1000000000;
const int maxn = 505;
int q,n,m,d[maxn][maxn][5],vis[maxn][maxn],x,y;
struct node {
int x,y,haha;
node(int x=0, int y=0, int haha=0):x(x),y(y),haha(haha) {}
bool operator == (const node& rhs) const {
return x == rhs.x && y == rhs.y;
}
}S;
char s[maxn][maxn];
int dx[] = {1,0,-1,0};
int dy[] = {0,1,0,-1};
int bfs(node S) {
queue<node> Q;
memset(d,-1,sizeof(d));
d[S.x][S.y][S.haha] = 0;
Q.push(S);
while(!Q.empty()) {
node u = Q.front(); Q.pop();
if(u.haha == ((1<<q)-1)) return d[u.x][u.y][u.haha];
for(int i=0;i<4;i++) {
node v = u;
v.x += dx[i]; v.y += dy[i];
if(v.x < 1 || v.x > n || v.y < 1 || v.y > m) continue;
if(vis[v.x][v.y] != -1)
v.haha |= (1<<vis[v.x][v.y]);
if(d[v.x][v.y][v.haha] == -1 && s[v.x][v.y] != '#') {
d[v.x][v.y][v.haha] = d[u.x][u.y][u.haha] + 1;
Q.push(v);
}
}
}
return -1;
}
int main() {
while(~scanf("%d%d",&n,&m)) {
if(!n && !m) break;
memset(vis,-1,sizeof(vis));
for(int i=1;i<=n;i++) scanf("%s",s[i]+1);
bool ok = false;
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
if(s[i][j] == '@') { S = node(i,j,0); ok = true; break; }
}
if(ok) break;
}
scanf("%d",&q);
for(int i=0;i<q;i++) {
scanf("%d%d",&x,&y);
vis[x][y] = i;
if(x == S.x && y == S.y)
S.haha |= (1<<i);
}
printf("%d\n",bfs(S));
}
return 0;
}