这题意思就是求出从起点到所给出来的点的所有点的最少路径数
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N=105;
int n,m,k;
int dir[4][2]= {{0,1},{0,-1},{1,0},{-1,0}};
char s[N][N];
int p[N][N];
bool hash[N][N][N];
int num;
struct node {
int x,y,step,key;
};
int bfs(int x,int y) {
int i;
queue<node>q;
node cur,next;
cur.x=x;
cur.y=y;
cur.step=0;
cur.key=0;
hash[cur.x][cur.y][cur.key]=1;
q.push(cur);
while(!q.empty()) {
cur=q.front();
q.pop();
if(cur.key==num)return cur.step;
for(i=0; i<4; i++) {
next.x=cur.x+dir[i][0];
next.y=cur.y+dir[i][1];
if(next.x<0||next.x>=n||next.y<0||next.y>=m||s[next.x][next.y]=='#')continue;
next.step=cur.step+1;
next.key=cur.key;
if(p[next.x][next.y])next.key=(next.key|(1<<(p[next.x][next.y]-1)));
if(!hash[next.x][next.y][next.key]) {
hash[next.x][next.y][next.key]=1;
q.push(next);
}
}
}
return -1;
}
int main() {
int i ,j,x,y,flag1,flag2,flag3,r;
while(scanf("%d%d",&n,&m),n+m) {
flag3=0;
num=1;
memset(p,0,sizeof(p));
for(i=0; i<n; i++)
scanf("%s",&s[i]);
scanf("%d",&k);
for( i=1; i<=k; i++) {
scanf("%d%d",&x,&y);
p[x-1][y-1]=i;
}
for(i=0; i<n; i++) {
for(j=0; j<m; j++) {
if(s[i][j]=='@') {
flag1=i;
flag2=j;
flag3=1;
break;
}
}
if(flag3)break;
}
for(i=0,r=1; i<k-1; i++) {
r=r*2;
num+=r;
}
int ans;
memset(hash,0,sizeof(hash));
ans=bfs(flag1,flag2);
printf("%d\n",ans);
}
return 0;
}
HDU 4771 BFS+状态压缩
最新推荐文章于 2020-08-28 22:24:59 发布