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

Posted shuiyonglewodezzzzz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}

 

以上是关于uva-10085-搜索-最远状态的八数码的主要内容,如果未能解决你的问题,请参考以下文章

BFS-八数码问题与状态图搜索

论久违的八数码问题——小试牛刀

UVA10085-不知错在何处

HDU 1043 Eight八数码解题思路(bfs+hash 打表 IDA* 等)

八数码的A*与IDA*算法-搜索进阶练习1

广度优先搜索解决八数码问题