#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int n;
char graph[55][55];
bool vis[55][55][55];
int a,b,c; //三个物品的位置
struct node{
int pos[3]; //当前状态下,三个物品的位置
char step;
}st;
void bfs(){
vis[st.pos[0]][st.pos[1]][st.pos[2]] = 1 ; //标记当前状态已经访问过
queue<node> q;
q.push(st);
while(!q.empty()){
node t = q.front();
q.pop();
for(int i=0;i<3;i++){ //移动哪个节点
for(int j=1;j<=n;j++){ //将i号节点移动到哪个位置j上
node next = t;
int n1 = (i+1)%3; //当前节点的两个其他节点
int n2 = (i+2)%3;
if(graph[next.pos[i]][j] == graph[next.pos[n1]][next.pos[n2]]){
//是否满足移动的约束条件,即要移动的边的颜色和其他两个点之间边的颜色相同
next.pos[i] = j; //满足条件,则将i物品节点移动到j号节点上去
if(!vis[next.pos[0]][next.pos[1]][next.pos[2]]){ //若当前状态未访问过
vis[next.pos[0]][next.pos[1]][next.pos[2]] = true;
next.step++; //移动记数加一
q.push(next);
if(next.pos[0]==next.pos[1] && next.pos[1]==next.pos[2]){
printf("%d\n",next.step);
return ;
}
}
}
}
}
}
printf("impossible\n");
}
int main(){
while(scanf("%d",&n) && n){
st.step = 0;
memset(vis,0,sizeof(vis));
scanf("%d%d%d",&a,&b,&c); //一定有三个点
st.pos[0] = a;
st.pos[1] = b;
st.pos[2] = c;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf(" %c",&graph[i][j]);
if(a==b && b==c) printf("0\n");
else
bfs();
}
return 0;
}
HDU 1252 Hike on a Graph bfs
最新推荐文章于 2020-03-09 17:17:19 发布