poj 1077 Eight(经典八数码问题:bfs/Dbfs)

poj 2814 拨钟问题(枚举) 程序设计实习枚举作业 拨钟问题 阅读详情

poj 1077 Eight(经典八数码问题:bDfs/Dbfs)
总时间限制: 5000ms 内存限制: 65536kB

Special Judge

描述
The 15-puzzle has been around for over 100 years; even if you don’t know it by that name, you’ve seen it. It is constructed with 15 sliding tiles, each with a number from 1 to 15 on it, and all packed into a 4 by 4 frame with one tile missing. Let’s call the missing tile ‘x’; the object of the puzzle is to arrange the tiles so that they are ordered as:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 x

where the only legal operation is to exchange ‘x’ with one of the tiles with which it shares an edge. As an example, the following sequence of moves solves a slightly scrambled puzzle:
这里写图片描述
The letters in the previous row indicate which neighbor of the ‘x’ tile is swapped with the ‘x’ tile at each step; legal values are ‘r’,’l’,’u’ and ‘d’, for right, left, up, and down, respectively.

Not all puzzles can be solved; in 1870, a man named Sam Loyd was famous for distributing an unsolvable version of the puzzle, and
frustrating many people. In fact, all you have to do to make a regular puzzle into an unsolvable one is to swap two tiles (not counting the missing ‘x’ tile, of course).

In this problem, you will write a program for solving the less well-known 8-puzzle, composed of tiles on a three by three
arrangement.

输入
You will receive a description of a configuration of the 8 puzzle. The description is just a list of the tiles in their initial positions, with the rows listed from top to bottom, and the tiles listed from left to right within a row, where the tiles are represented by numbers 1 to 8, plus ‘x’. For example, this puzzle
1 2 3
x 4 6
7 5 8

is described by this list:

1 2 3 x 4 6 7 5 8

输出
You will print to standard output either the word “unsolvable”, if the puzzle has no solution, or a string consisting entirely of the letters ‘r’, ‘l’, ‘u’ and ‘d’ that describes a series of moves that produce a solution. The string should include no spaces and start at the beginning of the line.

样例输入

2 3 4 1 5 x 7 6 8

样例输出

ullddrurdllurdruldr

来源
South Central USA 1998


本题是经典八数码问题,这一次以这道题为契机学习了Dbfs,现在已经学会了用bfs(version 1)和Dbfs(version 2)实现了。注意本题是special judge的,这样才不必考虑合理的搜索顺保证字典序,否则Dbfs无法安排搜索顺序…

注意一个编码小技巧Cantor launched,用来给全排列编码而且很节省空间。以后要用了推一推还是可以记起来的。

下面是代码(含测试部分)和评测结果,可以发现Dbfs快于bfs

version 1

Accepted    9140kB  220ms  2398 B   G++
#define TEST
#undef TEST

#define MAX_LEN 362880
#define TARGET_STATE 46233

#include<stdio.h>
#include<iostream>

using namespace std;

const char operate_name[4]={'u','d','l','r'};
const int change[9][4]={{-1, 3,-1, 1},{-1, 4, 0, 2},{-1, 5, 1,-1},
                        { 0, 6,-1, 4},{ 1, 7, 3, 5},{ 2, 8, 4,-1},
                        { 3,-1,-1, 7},{ 4,-1, 6, 8},{ 5,-1, 7,-1}};
/*
 * 0 1 2 
 * 3 4 5
 * 6 7 8
 */

int queue[MAX_LEN][9];
int blank[MAX_LEN],father[MAX_LEN],operate[MAX_LEN];
int head,tail;

char str_out[MAX_LEN];
int len; 

bool visit[MAX_LEN];

int cantor_launched(int a[]);
void read_and_init();
void bfs();
void print(int last);
void test();

int main()
{
#ifdef TEST
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
#endif
    read_and_init();
    bfs();
#ifdef TEST
    test();
#endif
    return 0;
}

int cantor_launched(int a[])
{
    int anti_num,frac=1,ans=0;
    for (int i=8;i>=0;i--)
    {
        anti_num=0;
        for (int j=i;j<9;j++)
            if (a[j]<a[i])
                anti_num++;
        ans+=frac*anti_num;
        frac*=(9-i);
    }
    return ans;
}

void read_and_init()
{
    char ch;
    for (int i=0;i<9;i++)
    {
        cin>>ch;
        if (ch=='X' || ch=='x')
        {
            blank[0]=i;
            queue[0][i]=0;
        }
        else
            queue[0][i]=ch-'0';
    }
    head=0;
    tail=0;
    father[0]=0;
    operate[0]=0;
    return;
}

void bfs()
{
    int new_blank;
    while (head<=tail)
    {
        if (cantor_launched(queue[head])==TARGET_STATE)
        {
            print(head);
            return;
        }
        for (int d=0;d<4;d++)
        {
            new_blank=change[blank[head]][d];
            if (new_blank!=-1)
            {
                tail++;
                for (int i=0;i<9;i++)
                    queue[tail][i]=queue[head][i];
                queue[tail][new_blank]=0;
                queue[tail][blank[head]]=queue[head][new_blank];
                if (visit[cantor_launched(queue[tail])])
                    tail--;
                else
                {
                    visit[cantor_launched(queue[tail])]=true;
                    blank[tail]=new_blank;
                    father[tail]=head;
                    operate[tail]=d;
                }
            }
        }
        head++;
    }
    printf("unsolvable\n");
    return;
}

void print(int last)
{
    while (father[last]!=last)
    {
        str_out[len++]=operate_name[operate[last]];
    #ifdef TEST
        printf("\n"); 
        for (int t=0;t<9;t++)
            printf("%d%c",queue[last][t],(t+1)%3?' ':'\n');
    #endif
        last=father[last];
    }
    for (int i=len-1;i>=0;i--)
        printf("%c",str_out[i]);
    printf("\n"); 
    return;
}

void test()
{
    for (int i=0;i<tail;i++)
    {
        for (int t=0;t<9;t++)
            printf("%d%c",queue[i][t],(t+1)%3?' ':'\n');
        printf("father=%d,operate=%d\n\n",father[i],operate[i]); 
    }
    return;
}

version 2

Accepted    1928kB  0ms 4690 B  G++ 
#define TEST
#undef TEST

#define MAX_LEN 362880
#define TARGET_STATE 46233

#include<stdio.h>
#include<iostream>

using namespace std;

const char operate_name[4]={'u','d','l','r'};
const int change[9][4]={{-1, 3,-1, 1},{-1, 4, 0, 2},{-1, 5, 1,-1},
                        { 0, 6,-1, 4},{ 1, 7, 3, 5},{ 2, 8, 4,-1},
                        { 3,-1,-1, 7},{ 4,-1, 6, 8},{ 5,-1, 7,-1}};

const char operate_rname[4]={'d','u','r','l'};
const int rchange[9][4]={{ 3,-1, 1,-1},{ 4,-1, 2, 0},{ 5,-1,-1, 1},
                         { 6, 0, 4,-1},{ 7, 1, 5, 3},{ 8, 2,-1, 4},
                         {-1, 3, 7,-1},{-1, 4, 8, 6},{-1, 5,-1, 7}};
/*
 * 0 1 2 
 * 3 4 5
 * 6 7 8
 */

int queue[MAX_LEN+1][9];
int blank[MAX_LEN+1],father[MAX_LEN+1],operate[MAX_LEN+1];
int head,tail,rhead,rtail;

char str_out[MAX_LEN];
int len; 

bool visit[MAX_LEN],rvisit[MAX_LEN];

int cantor_launched(int a[]);
void read_and_init();
void dbfs();
void print(int last);
void rprint(int last);


void test()
{
    printf("\n___________TEST___________\n");
    for (int i=0;i<tail;i++)
    {
        printf("\n");
        for (int t=0;t<9;t++)
            printf("%d%c",queue[i][t],(t+1)%3?' ':'\n');
        printf("father=%5d,operate=%5d\n",father[i],operate[i]); 
    }
    for (int i=rtail;i<=MAX_LEN;i++)
    {
        printf("\n");
        for (int t=0;t<9;t++)
            printf("%d%c",queue[i][t],(t+1)%3?' ':'\n');
        printf("father=%5d,operate=%5d\n",father[i],operate[i]); 
    }
    return;
}

int main()
{
#ifdef TEST
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
#endif
    read_and_init();
    dbfs();
#ifdef TEST
    test();
#endif
    return 0;
}

int cantor_launched(int a[])
{
    int anti_num,frac=1,ans=0;
    for (int i=8;i>=0;i--)
    {
        anti_num=0;
        for (int j=i;j<9;j++)
            if (a[j]<a[i])
                anti_num++;
        ans+=frac*anti_num;
        frac*=(9-i);
    }
    return ans;
}

void read_and_init()
{
    char ch;
    for (int i=0;i<9;i++)
    {
        cin>>ch;
        if (ch=='X' || ch=='x')
        {
            blank[0]=i;
            queue[0][i]=0;
        }
        else
            queue[0][i]=ch-'0';
    }
    head=0;
    tail=0;
    father[0]=0;
    operate[0]=0;
    visit[cantor_launched(queue[0])]=true;
    for (int i=0;i<8;i++)
        queue[MAX_LEN][i]=i+1;
    queue[MAX_LEN][8]=0;
    rhead=MAX_LEN;
    rtail=MAX_LEN;
    father[MAX_LEN]=MAX_LEN;
    operate[MAX_LEN]=0;
    blank[MAX_LEN]=8;
    rvisit[TARGET_STATE]=true;
    return;
}

void dbfs()
{
    int new_blank;
    while (head<=tail || rhead>=rtail)
    {
        if (head<=tail){
        if (rvisit[cantor_launched(queue[head])])
        {
            print(head);
            for (int j=rtail;j<=rhead;j++)
                if (cantor_launched(queue[head])==cantor_launched(queue[j]))
                {
                    rprint(j);
                    break;
                }
            return;
        }
        for (int d=0;d<4;d++)
        {
            new_blank=change[blank[head]][d];
            if (new_blank!=-1)
            {
                tail++;
                for (int i=0;i<9;i++)
                    queue[tail][i]=queue[head][i];
                queue[tail][new_blank]=0;
                queue[tail][blank[head]]=queue[head][new_blank];
                if (visit[cantor_launched(queue[tail])])
                    tail--;
                else
                {
                    visit[cantor_launched(queue[tail])]=true;
                    blank[tail]=new_blank;
                    father[tail]=head;
                    operate[tail]=d;
                }
            }
        }
        head++;}
        if (rhead>=rtail){
        if (visit[cantor_launched(queue[rhead])])
        {
            for (int j=head;j<=tail;j++)
                if (cantor_launched(queue[rhead])==cantor_launched(queue[j]))
                {
                    print(j);
                    break;
                }
            rprint(rhead);
            return;
        }
        for (int d=0;d<4;d++)
        {
            new_blank=rchange[blank[rhead]][d];
            if (new_blank!=-1)
            {
                rtail--;
                for (int i=0;i<9;i++)
                    queue[rtail][i]=queue[rhead][i];
                queue[rtail][new_blank]=0;
                queue[rtail][blank[rhead]]=queue[rhead][new_blank];
                if (rvisit[cantor_launched(queue[rtail])])
                    rtail++;
                else
                {
                    rvisit[cantor_launched(queue[rtail])]=true;
                    blank[rtail]=new_blank;
                    father[rtail]=rhead;
                    operate[rtail]=d;
                }
            }
        }
        rhead--;}
    }
    printf("unsolvable\n");
    return;
}

void print(int last)
{
#ifdef TEST
    printf("Steps pointers move:\nhead=%d,tail=%d,rhead=%d,rtail=%d\n",
            head,tail,MAX_LEN-rhead,MAX_LEN-rtail); 
    printf("%d\n",last); 
#endif
    while (father[last]!=last)
    {
        str_out[len++]=operate_name[operate[last]];
        last=father[last];
    #ifdef TEST
        printf("\n");
        for (int t=0;t<9;t++)
            printf("%d%c",queue[last][t],(t+1)%3?' ':'\n'); 
        printf("father=%5d,operate=%5d\n",father[last],operate[last]);
    #endif
    }
    for (int i=len-1;i>=0;i--)
        printf("%c",str_out[i]);
#ifdef TEST
    printf("\n");
#endif 
    return;
}

void rprint(int last)
{
#ifdef TEST
    printf("%d\n",last);
#endif
    len=0;
    while (father[last]!=last)
    {
        str_out[len++]=operate_name[operate[last]]; 
    #ifdef TEST
        printf("\n");
        for (int t=0;t<9;t++)
            printf("%d%c",queue[last][t],(t+1)%3?' ':'\n'); 
        printf("father=%5d,operate=%5d\n",father[last],operate[last]);
    #endif
        last=father[last];
    }
    str_out[len]=0;
    printf("%s\n",str_out);
    return;
}
【算法每日一练]-双向bfs 篇6 八数码难题(两个解法),噩梦 今天讲一下进阶版的bfs 阅读详情

相关推荐

hdu1043 Eight (八数码问题,多种解法)

hdu1043 :http://acm.hdu.edu.cn/showproblem.php?pid=1043 八数码问题       有一个3*3的棋盘,其中有0-8共9个数字,0表示空格,其他的数字可以和0交换位置。求由初始状态到达目标状态 123  456  780 的步数最少的解? 有多组数据 解法: 1、反向BFS + hash( cantor展开 ) 因为状态

天亮说晚安 4407

八数码问题bfsdbfs版本详解

hdu1043多组数据 poj1077单组数据 1、对于空间的处理 按常规方法,标志位序列vis的大小需要876543210位,空间非常大,所以我们考虑将int转化为char 类型储存(32位机int占4字节 char 占1字节)。 又考虑,如果转化为九进制,876543210(9)-->381367044(10),进一步优化空间。 可是像111111111,333333333这样...

weixin_30924239的博客 397

7种方法求解八数码问题

八数码问题】//https://vijos.org/p/1360 在3×3的棋盘上,摆有八个棋子,每个棋子上标有1至8的某一数字。棋盘中留有一个空格,空格用0来表示。空格周围的棋子可以移到空格中。要求解的问题是:给出一种初始布局(初始状态)和目标布局(为了使题目简单,设目标状态为123804765),找到一种最少步骤的移动方法,实现从初始布局到目标布局的转变。 【分析】 题目读完第一感

u012283461的博客 10万+

(洛谷 R6765172)八数码问题 DBFS+hash 乱搞

非常经典的一道搜索练手题,各种方法花式求解(虽然目前只搞定了 DBFS+hash,但是可以说说想法XD)题目描述:在3×3的棋盘上,摆有八个棋子,每个棋子上标有1至8的某一数字。棋盘中留有一个空格,空格用0来表示。空格周围的棋子可以移到空格中。要求解的问题是:给出一种初始布局(初始状态)和目标布局(为了使题目简单,设目标状态为123804765),找到一种最少步骤的移动方法,实现从初始布局到目标布...

adnyxlaer的博客 378

POJ 1077 Eight 八数码 DBFS

题目地址:http://poj.org/problem?id=1077 #include #include #include #include #include using namespace std; struct Node{ int status; int parent; int move; Node(int s=0,int p=0,int m=-1):status(s),paren

BRCOCOLI的博客 290

POJ1077八数码

POJ1077:八数码问题(Eight) POJ1077查看 文章目录POJ1077:八数码问题(Eight)@[toc]**解题思路**基础知识铺垫广度优先搜索BFS+康托展开广度优先搜索BFS+set二分查找双向广搜DBFS+set二分查找启发式算法+堆+普通标记数组更多策略 解题思路 求步数最少的解时候用广搜 状态的表示问题 若以字符串的形式表示,需要10字节,且检查是否达到目标状...

loveSiri的博客 1283

poj 1077 & hdu 1043 Eight ( 多种解法:预处理、bfsdbfs、IDA*、A*)

Eight Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 9114    Accepted Submission(s): 2450 Special Judge Problem Description The

To be what you what to be! 1259

poj 1077 Eightbfsdbfs, A*)

代码如下: bfs: 1 #include <iostream> 2 #include <map> 3 #include <algorithm> 4 #include <string> 5 #include <queue> 6 using namespace std; 7 typedef long long LL; 8...

月夜长影 93

POJ 1077 eight DBFS

和HDU1043一样的题目,这次用DBFS实现。 感觉写的还是不错的,中间一些细节错误了很多次。 具体见代码。 #include #include #include #include #include #include #include #include #include #include #include #include #define PI acos(-1.

just_water 1191

poj 1077 hdu 1043 Eight 八数码问题 DBFS(双向广度优先搜索)a*算法 康拓展开

一,八数码问题简介 编号为1到8的8个正方形滑块被摆成3行3列(有一个格子留空),可以每次把与空格相邻(有公共边)的滑块移动到空格中,而它原来的位置就成了新的空格。给定局面,计算出从当前状态移动到目标状态的最少步数。如将八数码从左到有从上到下的数字列出来,没有空格用0表示(其实也可以用9表示),可以表示为: 2 6 4 1 3 7 0 5 8 -> 8 1 5 7 3 6 4 0 2 在这里我们

gwq5210的专栏 1849

搜索 ( 八数码问题详解:BFS,A*,IDA* )——Eight ( POJ 1077 )

DBFS,A*,IDA*,转自链接 (侵删) 题目链接: http://poj.org/problem?id=2449 分析: 又称为九宫格问题,给出一个状态的九宫格,判断是否有解,如果有则输出解。 八数码问题有无解的结论:一个状态表示成一维的形式,求出除0之外所有数字的逆序数之和(每个数字前面比它大的数字的个数的和,称为这个状态的逆序)。 若两个状态的逆序数奇偶性相同,则可相互到达,否则不可相

FeBr2的博客 1112

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

八数码问题:在3×3的方格棋盘上,摆放着1到8这八个数码,有1个方格是空的,其初始状态如图1所示,要求对空格执行空格左移、空格右移、空格上移和空格下移这四个操作使得棋盘从初始状态到目标状态。                                           // eight.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h"

Marshall的专栏 5521

八数码问题小结

一. 八数码问题 八数码问题也称为九宫问题。在3×3的棋盘,摆有八个棋子,每个棋子上标有1至8的某一数字,不同棋子上标的数字不相同。棋盘上还有一个空格,与空格相邻的棋子可以移到空格中。要求解决的问题是:给出一个初始状态和一个目标状态,找出一种从初始转变成目标状态的移动棋子步数最少的移动步骤。 二. 问题分析 看到不错的文章,就直接传送门了,谁叫我这么懒呢。。。 八数码的八境界: http://www.cnblogs.com/goodness/archive/2010/05/04/1727141

luciozhang的博客 1万+

1043 Eight八数码问题 康托展开 A*算法)

首先介绍一下A*算法: https://blog.csdn.net/qq_40061421/article/details/81915573 然后是康托展开: https://blog.csdn.net/qq_40061421/article/details/81915838 A*:f=g+h函数。g表示从起点到当前点的移动步数,h表示对当前点到目标点的最小移动步数的预测。除去起点和目标点...

Geek 776

poj 1321 棋盘问题(深搜)

poj 1321 棋盘问题(深搜)

PKU_ZZY的博客 5674

poj 1190 生日蛋糕(深搜+剪枝技巧)

poj 1190 生日蛋糕(深搜+剪枝技巧)

PKU_ZZY的博客 5206
上一篇: poj 4105 拯救公主(bfs+二进制状态压缩)
下一篇: poj 4980 拯救行动(变式bfs)
pku_zzy
博客等级 码龄10年 144粉丝 182原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值