POJ2697-A Board Game

5 篇文章 0 订阅

将各个状态转换为字符串然后用map储存起来,用BFS即可。

//POJ2697
#include <cstdio>
#include <iostream>
#include <string>
#include <queue>
#include <map>
#include <algorithm>

using namespace std;

typedef pair<string, char> P;

int dx[3] = {-1, 0, 1};
int dy[3] = {-4, 0, 4};

char board[6][6];

string raw;
string res;

int Bfs() {
    queue<P> q;
    q.push(P(raw, 'w'));
    map<string, int> mp;
    mp[raw] = 0;

    while (!q.empty()) {
        P p = q.front();
        string s = p.first;
        char ch = p.second;
        q.pop();
        if (s == res) {
            return mp[s];
        }

        for (int i = 0; i < 16; i++) {
            if (s[i] == ch) {
                for (int x = 0; x < 3; x++) {
                    for (int y = 0; y < 3; y++) {
                        if (dx[x] == 0 && dy[y] == 0) {
                            continue;
                        }
                        int ni = i;
                        int ti = i + dx[x] + dy[y];
                        while (0 <= ti && ti < 16 && s[ti] == '*') {
                            ni += dx[x] + dy[y];
                            ti += dx[x] + dy[y];
                        }
                        int tmp = mp[s];
                        swap(s[i], s[ni]);
                        if (mp.find(s) == mp.end()) {
                            int c = (ch == 'w') ? 'b' : 'w';
                            q.push(P(s, c));
                            mp[s] = tmp + 1;
                        }
                        swap(s[i], s[ni]);
                    }
                }
            }
        }
    }
    return -1;
}

int main(int argc, char const *argv[]) {
    int w;
    scanf("%d%*c", &w);
    while (w--) {
        raw = "";
        res = "";
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                scanf("%c", &board[i][j]);
                raw += board[i][j];
            }
            getchar();
        }
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                scanf("%c", &board[i][j]);
                res += board[i][j];
            }
            getchar();
        }
        printf("%d\n", Bfs());
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值