题目链接:Hike on a Graph
题目大意,给定一个图,图上有n个点(0<=n<=50),每两个点由一条有颜色的边相连(有自环),有三个pieces,任务是将三个pieces移动到一个点上,求最小步数。每一步的要求是,假如第一个piece要从i移动的j,那么i和j之间的颜色必须和2和3两个peices之间的边的颜色相同。
题目分析:裸的bfs,开一个vis[maxn][maxn][maxn]记录三个pieces到达的状态判重
代码
#include <stdio.h>
#include <string.h>
#include <memory.h>
#include <queue>
#include <iostream>
using namespace std;
const int maxn=60;
char g[maxn][maxn];
bool vis[maxn][maxn][maxn];
int p1,p2,p3,n;
struct node
{
int p1,p2,p3;
int step;
};
int bfs()
{
queue<node>q;
memset(vis,0,sizeof(vis));
node cur,next;
cur.p1=p1;cur.p2=p2;cur.p3=p3;
cur.step=0;
q.push(cur);
vis[p1][p2][p3]=1;
while(!q.empty()){
cur=q.front();
q.pop();
if(cur.p1==cur.p2&&cur.p2==cur.p3)return cur.step;
for(int i=1;i<=n;i++){
if(g[cur.p1][i]==g[cur.p2][cur.p3]&&!vis[i][cur.p2][cur.p3]){
next=cur;
next.step+=1;
next.p1=i;
q.push(next);
vis[i][next.p2][next.p3]=1;
}
if(g[cur.p2][i]==g[cur.p1][cur.p3]&&!vis[cur.p1][i][cur.p3]){
next=cur;
next.step+=1;
next.p2=i;
q.push(next);
vis[next.p1][i][next.p3]=1;
}
if(g[cur.p3][i]==g[cur.p1][cur.p2]&&!vis[cur.p1][cur.p2][i]){
next=cur;
next.step+=1;
next.p3=i;
q.push(next);
vis[next.p1][next.p2][i]=1;
}
}
}
return -1;
}
int main()
{
//freopen("in.txt","r",stdin);
char c;
while(scanf("%d",&n)!=EOF&&n){
scanf("%d %d %d",&p1,&p2,&p3);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
scanf("%s",&g[i][j]);
}
}
int ans=bfs();
if(ans!=-1)printf("%d\n",ans);
else printf("impossible\n");
}
return 0;
}