码迷,mamicode.com
首页 > 其他好文 > 详细

hdu Hike on a Graph

时间:2015-04-16 23:28:35      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:

此题是道bfs搜索的题目。bfs的精髓就是找到下一步的所有可能然后存储起来,有点暴力的感觉,这题就是每步中 所有的可能都入队,然后一一 判断。这道题的题意是 :

给你一幅完全图,再给你三个盘,目的是把这三个盘移动到一个点上,输出最少步数!盘移动的时候有要求,比如移第一个盘,把1盘移动到2这个位置,(1,2)这个点有颜色标记,另外两个盘比如说在3,4两点,那么1盘能移动到2这个点的条件是(1,2)这个点的颜色要与(3,4)这点的颜色相同!!

技术分享
#include"iostream"
#include"stdio.h"
#include"algorithm"
#include"string.h"
#include"cmath"
#include"string"
#include"queue"
#define mx 105
using namespace  std;
int n,p1,p2,p3;
struct node
{
    int p[3];
    int step;
};
char g[mx][mx];
bool vis[mx][mx][mx];//标记某种情况是否已出现过

void Set(node a)
{
    vis[a.p[0]][a.p[1]][a.p[2]]=false;
}

bool judge(node a) //判断此情况是否已出现过
{
    return vis[a.p[0]][a.p[1]][a.p[2]];
}

bool End(node a) //判断是否完成操作
{
    if(a.p[0]==a.p[1]&&a.p[1]==a.p[2]) return true;
    return false;
}

void bfs()
{
    queue<node>q;
    while(!q.empty()) q.pop();
    node cur,next;
    cur.p[0]=p1;cur.p[1]=p2;cur.p[2]=p3;cur.step=0;
    q.push(cur);
    Set(cur);
    int i;
    while(!q.empty())
    {
        cur=q.front();
        q.pop();
        if(End(cur))
        {
            cout<<cur.step<<endl;
            return;
        }
        for(i=1;i<=n;i++)
        {
            next=cur;
            next.p[0]=i;
            next.step++;
            if(judge(next)&&g[cur.p[0]][i]==g[cur.p[1]][cur.p[2]])
            {
                Set(next);
                q.push(next);
            }
        }
          for(i=1;i<=n;i++)
        {
            next=cur;
            next.p[1]=i;
            next.step++;
            if(judge(next)&&g[cur.p[1]][i]==g[cur.p[0]][cur.p[2]])
            {
                Set(next);
                q.push(next);
            }
        }
          for(i=1;i<=n;i++)
        {
            next=cur;
            next.p[2]=i;
            next.step++;
            if(judge(next)&&g[cur.p[2]][i]==g[cur.p[1]][cur.p[0]])
            {
                Set(next);
                q.push(next);
            }
        }
    }
    cout<<"impossible"<<endl;
}
int main()
{
    int i,j;
    while(cin>>n,n)
    {
        memset(vis,true,sizeof(vis));
        cin>>p1>>p2>>p3;
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=n;j++)
            {
                cin>>g[i][j];//用于单个字符的输入,不会读入空格,以前一直误以为会连空格一起读入
            }
        }
        bfs();
    }
    return 0;
}
View Code

 

hdu Hike on a Graph

标签:

原文地址:http://www.cnblogs.com/acm-jing/p/4433539.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!