POJ 1077 Eight (classic eight digital question: BFS/DBFS) __algorithm

Source: Internet
Author: User
Tags stdin

POJ 1077 Eight (classic eight digital problem: BDFS/DBFS)
Total time limit: 5000ms memory limit: 65536kB

Special Judge

Describe
The 15-puzzle has been around for over years; Even if you don ' t know it through that name, ' ve seen it. It is constructed with sliding tiles, each with a number from 1 to, and all packed into a 4 through 4 frame with on E tile missing. Let ' s call the missing tile ' x '; The object of the puzzle is to arrange the tiles so they are as:
1 2 3 4
5 6 7 8
9 10 11 12
EUR x

Where the only legal operation are to Exchange ' X ' and one of the tiles with which it shares a 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 are swapped with the ' X ' tile on 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 is famous for distributing a unsolvable version of the puzzle, and
Frustrating many people. In fact, all your have to a regular puzzle into a unsolvable one-to-swap two tiles (not counting the missing ' X ' tile, of course).

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

Input
You 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 T Iles 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

Output
You'll print to standard output either the word "unsolvable", if the puzzle has no solution, or a string consisting Enti Rely 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.

Sample input

2 3 4 1 5 x 7 6 8

Sample output

Ullddrurdllurdruldr

Source
South, USA 1998

This is the classic eight-digit problem, this time with the title of the opportunity to learn dBFS, now has learned to use BFS (version 1) and dBFS (version 2) implemented. Note that the subject is special judge, so that you do not have to consider reasonable search shun guarantee dictionary order, or DBFS can not arrange the search order ...

Note that a coding trick Cantor launched is used to encode the entire array and save space. Later to use a push or can be remembered.

Here is the code (including the test section) and the evaluation results, you can find dBFS faster than 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&

Gt

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&

Gt

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)) {PR
  Int (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 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.