POJ2697(BFS)

题目链接:http://poj.org/problem?id=2697

只是状态的储存问题,可以把棋盘拉成长度为16的字符串,用map来储存就可以。

#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <queue>
#include <map>
#include <string>
using namespace std;

const int dx[8] = {-1,-1,-1,0,0,1,1,1};
const int dy[8] = {-1,0,1,-1,1,-1,0,1};

map<string,bool> f;
struct node
{
    string state;
    int step;
    char col;
};
node st,ed;
queue<node> Q;

void init()
{
    st.state = "";
    for (int i=0; i<4; i++)
    {
        char str[5];
        scanf("%s",str);
        getchar();
        for (int j=0; j<4; j++)
            st.state = st.state + str[j];
    }
    st.step = 0;
    ed.state = "";
    for (int i=0; i<4; i++)
    {
        char str[5];
        scanf("%s",str);
        getchar();
        for (int j=0; j<4; j++)
            ed.state = ed.state + str[j];
    }
}

bool next(node& now, int pos, int j)
{
    int nowi = pos/4;
    int nowj = pos - nowi*4;
    int newi = nowi+dx[j], newj = nowj+dy[j];
    int newpos = newi*4+newj;
    int cnt = 0;

    while (newi>=0 && newi<=3 && newj>=0 && newj<=3 && now.state[newpos]=='*')
    {
        cnt++;
        now.state[newpos] = now.state[pos];
        now.state[pos] = '*';
        newi = newi+dx[j]; newj = newj+dy[j];
        pos = newpos;
        newpos = newi*4+newj;
    }
    now.step++;

    return cnt;
}

int BFS()
{
    while (!Q.empty()) Q.pop();
    f.clear();

    st.col = 'b';
    Q.push(st);
    st.col = 'w';
    Q.push(st);
    f[st.state] = 1;
    while (!Q.empty())
    {
        node now = Q.front();
        node tmp = now;
        Q.pop();
        for (int i=0; i<16; i++)
                if (now.state[i] != '*' && now.state[i] != now.col)
            for (int j=0; j<8; j++)
        {
            if (!next(now,i,j))
            {
                now = tmp;
                continue;
            }
            node New = now;
            New.col = now.col == 'b' ? 'w' : 'b';
            now = tmp;
            if (New.state == ed.state)
                return New.step;

            if (f[New.state] == 0)
            {
                f[New.state] = 1;
                Q.push(New);
            }
        }
    }

    return -1;
}

int main()
{
    int t;

    scanf("%d",&t);
    getchar();
    while (t > 0)
    {
        t--;

        init();

        printf("%d\n",BFS());


    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值