蓝桥杯九宫重排(bfs+用set去重)

题目连接

#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<iostream>
#include<queue> 
#include<cmath>
#include<set>
#include<cstring>
using namespace std;
char s[4][4], e[4][4];
char  a[10];
struct point {
    int x, y;
    char status[4][4];
    int cnt = 0;
    point() {
    };
    point(int x, int y, char s[4][4] , int cnt) {
        this->x = x; this->y = y;
        for (int i = 0; i<3; i++)
            for (int j = 0; j<3; j++) {
            this->status[i][j] = s[i][j];
        }
        this->cnt = cnt;
    }
}p;
int ll;
int dx[4] = { 0,1,0,-1 };
int dy[4] = { -1,0,1,0 };
bool is_ok(int x, int y) {
    if (x<0 || x>2 || y<0 || y>2)return false;
    return true;
}
bool check(char(*s)[4], char(*e)[4]) {
    for (int i = 0; i<3; i++)
        for (int j = 0; j<3; j++) {
            if (s[i][j] != e[i][j])return false;
        }
    return true;
}
queue<point>que;
set<int>vis;
bool  change(char (*s)[4]) {
    
    int ans = 0;
    for (int i = 0; i < 3; i++)
    for(int j=0;j<3;j++){
        if (s[i][j] == '.')ans = ans * 10;
        else ans = ans * 10 + s[i][j] - '0';
    }
    if (vis.count(ans)) //容器中有相同 
    {
        return 0;
    }
    vis.insert(ans);//插入容器 
    return 1;
}
void bfs() {
    char temp[4][4];
    while (!que.empty()) {
        p = que.front();
        que.pop();
        if (check(p.status,e)) {
            cout << p.cnt << endl;
            return;
        }
        for (int i = 0; i<4; i++) {
            int x = p.x + dx[i];
            int y = p.y + dy[i];
            if (is_ok(x, y)) {
                memcpy(temp, p.status,sizeof(temp));
                temp[p.x][p.y] = temp[x][y];
                temp[x][y] = '.';
                if (change(temp)) {
                    que.push(point(x, y, temp, p.cnt + 1));
                }
                
            }
        }
    }
}
int main() {
    scanf("%s", a);
    int c = 0;
    int dxx, dyy;
    for (int i = 0; i<3; i++)
        for (int j = 0; j<3; j++) {
            if (a[c] == '.') {
                dxx = i, dyy= j;
            }
            s[i][j] = a[c++];
        }
    que.push(point(dxx, dyy, s, 0));
    change(s);
    c = 0;
    scanf("%s", a);
    for (int i = 0; i<3; i++)
        for (int j = 0; j<3; j++) {
            e[i][j] = a[c++];
        }
    bfs();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值