HDU 1252 Hike on a Graph bfs

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值