uva-10085-搜索-最远状态的八数码

直接bfs即可,取最后一个状态

#include <iostream>
#include <stdio.h>
#include <string>
#include <map>
#include <queue>

using namespace std;

struct Dir
{
        int x, y;
};

struct Node
{
        int x, y;
        string str = "";
        string steps = "";
};
char st[] = { 'U', 'D', 'L', 'R' };
Dir dir[] = { { 0, -1 }, { 0, 1 }, { -1, 0 }, { 1, 0 } };

queue<Node> q;
const int N = 5;
string ans = "";
string ansStep = "";

int index(int x, int y)
{
    return y * 3 + x;
}

void bfs(map<string, int> repeatMaps)
{
    while (!q.empty())
    {
        Node node = q.front();
        q.pop();
        int curZero = index(node.x, node.y);
        string curStr = node.str;
        for(int i = 0; i < 4; i++)
        {
            int nx = node.x + dir[i].x;
            int ny = node.y + dir[i].y;
            if(nx < 0 || ny < 0 || nx > 2 || ny > 2)
                continue;
            //nextstr
            string nextStr(curStr);
            swap(nextStr[index(nx, ny)], nextStr[curZero]);
            if(repeatMaps.find(nextStr) == repeatMaps.end())
            {
                //未重复
                Node n;
                n.str = nextStr;
                n.x = nx;
                n.y = ny;
                n.steps = node.steps + st[i];
                q.push(n);
                ans = nextStr;
                ansStep = n.steps;
                repeatMaps[nextStr] = 0;
            }
        }
    }
}

int main()
{
    freopen("d://1.text", "r", stdin);
    //3x3图
    //目标图
    int n;
    cin >> n;
    int t =1;
    while (n--)
    {
        if(t!=1)
            cout<<endl;
        string str = "";
        int k;
        int x, y;
        for(int i = 0; i < 3; i++)
            for(int j = 0; j < 3; j++)
            {
                cin >> k;
                str += k+'0';
                if(k == 0)
                {
                    y = i;
                    x = j;
                }
            }
        Node init;
        init.steps = "";
        init.str = str;
        init.x = x;
        init.y = y;
        q.push(init);
        map<string, int> repeatMaps;
        repeatMaps[str] = 0;
        bfs(repeatMaps);
        cout<<"Puzzle #"<<t<<endl;
        for(int i=0;i<3;i++)
        {
            for(int j=0;j<3;j++)
            {
                if(j!=0)
                {
                    cout<<" ";
                }
                cout<<ans[i*3+j];
            }
            cout<<endl;
        }
        cout << ansStep << endl;
        ++t;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/shuiyonglewodezzzzz/p/9387515.html