社区讨论

bfs 79pts求条

P1379八数码难题参与者 1已保存回复 0

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
0 条
当前快照
1 份
快照标识符
@m03jm5yv
此快照首次捕获于
2024/08/21 15:39
2 年前
此快照最后确认于
2025/11/04 22:51
4 个月前
查看原帖
CPP
#include <bits/stdc++.h>
#define int long long
#define endl "\n"

using namespace std;

int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
struct st
{
    char c[5][5] = {};
    string ts()
    {
        string ret = "";
        for(int i = 1; i <= 3; i++)
        {
            for(int j = 1; j <= 3; j++)
            {
                ret.push_back(c[i][j]);
            }
        }
        return ret;
    }
} beg;

string aim = "123804765";

bool operator< (st x, st y)
{
    return x.ts() < y.ts();
}

map<st, bool> vis; 

struct node
{
    st sta;
    int step;
};

void bfs()
{
    queue<node> que;
    que.push({beg, 0});
    while(!que.empty())
    {
        node h = que.front();
        que.pop();
        // cout << "h == " << h.sta.ts() << endl;
        if(h.sta.ts() == aim)
        {
            cout << h.step;
            return;
        }
        int x = -1, y = -1;
        for(int i = 1; i <= 3; i++)
        {
            for(int j = 1; j <= 3; j++)
            {
                if(h.sta.c[i][j] == '0')
                {
                    x = i;
                    y = j;
                    break;
                }
            }
            if(x != -1)
            {
                break;
            }
        }
        for(int i = 0; i < 4; i++)
        {
            int r = x + dx[i];
            int c = y + dy[i];
            if(r < 1 || c < 1 || r > 3 || c > 3)
            {
                continue;
            }
            st ns;
            for(int i = 1; i <= 3; i++)
            {
                for(int j = 1; j <= 3; j++)
                {
                    ns.c[i][j] = h.sta.c[i][j];
                }
            }
            swap(ns.c[x][y], ns.c[r][c]);
            if(vis[ns])
            {
                continue;
            }
            // cout << "   i == " << i << ", ns == " << endl;
            // for(int i = 1; i <= 3; i++)
            // {
            //     cout << "   ";
            //     for(int j = 1; j <= 3; j++)
            //     {
            //         cout << ns.c[i][j];
            //     }
            //     cout << endl;
            // }
            // cout << endl;
            vis[ns] = 1;
            que.push({ns, h.step + 1});
        }
    }
}

signed main()
{
    string s;
    cin >> s;
    int id = 0;
    for(int i = 1; i <= 3; i++)
    {
        for(int j = 1; j <= 3; j++)
        {
            beg.c[i][j] = s[id++];
        }
    }
    bfs();

    return 0;
}

回复

0 条回复,欢迎继续交流。

正在加载回复...