Eight POJ - 1077

原创 2018年04月16日 16:14:48

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:
 1  2  3  4    1  2  3  4    1  2  3  4    1  2  3  4 

 5  6  7  8    5  6  7  8    5  6  7  8    5  6  7  8 

 9  x 10 12    9 10  x 12    9 10 11 12    9 10 11 12 

13 14 11 15   13 14 11 15   13 14  x 15   13 14 15  x 

           r->           d->           r-> 

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.
Input
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 
Output
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.
Sample Input
 2  3  4  1  5  x  7  6  8 
Sample Output
ullddrurdllurdruldr

#include<stdio.h>
#include<iostream>
#include<string>
#include<queue>
#include<string.h>
#include<algorithm>
#define N 370000
const int n=9;
using namespace std;

int path[N],pre[N],vis[N],p[N];
int nx[4][2]= {-1,0,0,1,1,0,0,-1};
char st[5]= {'u','r','d','l'};
int ans[10]= {1,1,2,6,24,120,720,5040,40320};
struct node
{
    int num[10];
    int wz;
    int kt;
    int step;
};

int KT(int s[])
{
    int sum=0;
    for(int i=0; i<n; i++)
    {
        int res=0;
        for(int j=i+1; j<n; j++)
            if(s[i] > s[j]) res++;
        sum+=res*ans[n-1-i];
    }
    return sum;
}

void bfs(node a)
{
    node now,tmp;
    now=a;
    now.kt=KT(now.num);
    vis[now.kt]=1;
    now.step=0;
    queue<node>Q;
    Q.push(now);

    while(!Q.empty())
    {
        now=Q.front();
        Q.pop();
        if(now.kt==0)
        {
            int g=now.kt;
            for(int i=now.step; i>=1; i--)
            {
                p[i]=path[g]; //路径
                g=pre[g];  //前面的kt
            }
            for(int i=1; i<=now.step; i++)
                printf("%c",st[p[i]]);
            printf("\n");
            return ;
        }
        int tx,ty,x=now.wz/3,y=now.wz%3;
        for(int i=0; i<4; i++)
        {
            tx=x+nx[i][0];
            ty=y+nx[i][1];
            if(tx<0 || ty<0 ||tx>=3 || ty>=3) continue;
            for(int j=0; j<n; j++)
                tmp.num[j]=now.num[j];
            tmp.wz=tx*3+ty;
            swap(tmp.num[tmp.wz],tmp.num[now.wz]);
            tmp.kt=KT(tmp.num);
            if(vis[tmp.kt]) continue;
            vis[tmp.kt]=1;
            path[tmp.kt]=i;
            pre[tmp.kt]=now.kt;
            tmp.step=now.step+1;
            Q.push(tmp);
        }
    }
    printf("unsolvable\n");
}

int main()
{
    node now;
    char s;
    memset(vis,0,sizeof(vis));
    for(int i=0; i<n; i++)
    {
        cin>>s;
        if(s=='x')
        {
            now.num[i]=9;
            now.wz=i;
        }
        else
            now.num[i]=s-'0';
    }
    bfs(now);
    return 0;
}

用IDA* 时间更短 内存更小

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
using namespace std;

int mp[3][3],limit,flag;
int nx[4][2]= {0,-1,-1,0,0,1,1,0};
int ans[101];
char str[5]= {"lurd"};

int getall(int s[3][3])
{
    int sum=0;
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
        {
            if(s[i][j]==9) continue;
            if(s[i][j]-1 != i*3+j)
                sum+=fabs((s[i][j]-1)/3-i)+fabs((s[i][j]-1)%3-j);
        }
    return sum;
}

void dfs(int x,int y,int s,int pev)
{
    if(flag || s+getall(mp)>limit) return ;
    if(getall(mp)==0)
    {
        flag=1;
        for(int i=0; i<s; i++)
            printf("%c",str[ans[i]]);
        printf("\n");
        return ;
    }
    for(int i=0; i<4; i++)
    {
        int tx=x+nx[i][0];
        int ty=y+nx[i][1];
        if(tx<0 || ty<0 || tx>=3 || ty>=3 || fabs(pev-i)==2) continue;
        swap(mp[tx][ty],mp[x][y]);
        ans[s]=i;
        dfs(tx,ty,s+1,i);
        swap(mp[tx][ty],mp[x][y]);
    }
}

int main()
{
    char s;
    int x,y;
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            cin>>s;
            if(s=='x')
            {
                mp[i][j]=9;
                x=i;
                y=j;
            }
            else mp[i][j]=s-'0';
        }
    }
    flag=0;
    for(limit=getall(mp); limit<100; limit++)
    {
        dfs(x,y,0,-100);
    }
    if(!flag) printf("unsolvable\n");
    return 0;
} 

加了逆序数

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
using namespace std;

int mp[3][3],limit,flag;
int nx[4][2]= {0,-1,-1,0,0,1,1,0};
int ans[101];
char str[5]= {"lurd"};

int ok(int s[3][3])
{
    int sum=0,k=0,a[10];
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
            a[k++]=s[i][j];

    for(int i=0; i<9; i++)
    {
        for(int j=0; j<i; j++)
            if(a[i] < a[j] && a[j]!=9 && a[i]!=9) //只考虑1-8的位置关系
                sum++;
    }

    if(sum&1) return 0;
    return 1;
}

int getall(int s[3][3])
{
    int sum=0;
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
        {
            if(s[i][j]==9) continue;
            if(s[i][j]-1 != i*3+j)
                sum+=fabs((s[i][j]-1)/3-i)+fabs((s[i][j]-1)%3-j);
        }
    return sum;
}

void dfs(int x,int y,int s,int pev)
{
    if(flag || s+getall(mp)>limit) return ;
    if(getall(mp)==0)
    {
        flag=1;
        for(int i=0; i<s; i++)
            printf("%c",str[ans[i]]);
        printf("\n");
        return ;
    }
    for(int i=0; i<4; i++)
    {
        int tx=x+nx[i][0];
        int ty=y+nx[i][1];
        if(tx<0 || ty<0 || tx>=3 || ty>=3 || fabs(pev-i)==2) continue;
        swap(mp[tx][ty],mp[x][y]);
        if(!ok(mp)) continue;
        ans[s]=i;
        dfs(tx,ty,s+1,i);
        swap(mp[tx][ty],mp[x][y]);
    }
}

int main()
{
    char s;
    int x,y;
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            cin>>s;
            if(s=='x')
            {
                mp[i][j]=9;
                x=i;
                y=j;
            }
            else mp[i][j]=s-'0';
        }
    }
    if(!ok(mp))
    {
        printf("unsolvable\n");
        return 0;
    }
    flag=0;
    for(limit=getall(mp); limit<100 && !flag; limit++)
    {
        dfs(x,y,0,-100);
    }
    if(!flag) printf("unsolvable\n");
    return 0;
}

A*

#include<iostream>
#include<string.h>
#include<queue>
#include<math.h>
#define N 370000
using namespace std;

int path[N],pre[N],p[N],vis[N];
int ans[10]= {1,1,2,6,24,120,720,5040,40320};
int nx[4][2]= {0,-1,-1,0,0,1,1,0};
char str[5]= {"lurd"};
struct node
{
    int wz,kt;
    int num[10];
    int step;
    int has;
    bool operator < (const node &a) const
    {
        if(has==a.has) return step > a.step;
        return has >a.has;
    }
};

int ok(int s[])
{
    int sum=0;
    for(int i=0; i<9; i++)
    {
        for(int j=0; j<i; j++)
            if(s[i]!=9 && s[j]!=9 && s[i]<s[j]) sum++;
    }
    if(sum&1) return 0;
    return 1;
}

int hash_(int s[])
{
    int sum=0,k=0;
    int a[3][3];
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
            a[i][j]=s[k++];
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
        {
            if(a[i][j]==9) continue;
            if(a[i][j]!=i*3+j+1)
                sum+=fabs((a[i][j]-1)/3-i)+fabs((a[i][j]-1)%3-j);
        }
    return sum;
}

int KT(int s[])
{
    int res=0;
    for(int i=0; i<9; i++)
    {
        int v=0;
        for(int j=i+1; j<9; j++)
            if(s[i] > s[j])
                v++;
        res+=v*(ans[8-i]);
    }
    return res;
}

void bfs(node a)
{
    node now,tmp;
    now=a;
    priority_queue<node>Q;
    Q.push(now);

    while(!Q.empty())
    {
        now=Q.top();
        Q.pop();

        if(now.kt==0)
        {
            int g=now.kt;
            for(int i=now.step; i>=1; i--)
            {
                p[i]=path[g];
                g=pre[g];
            }
            for(int i=1; i<=now.step; i++)
                cout<<str[p[i]];
            cout<<endl;
            return ;
        }
        for(int i=0; i<4; i++)
        {
            int tx=now.wz/3+nx[i][0];
            int ty=now.wz%3+nx[i][1];
            if(tx<0 || ty<0 || tx>=3 || ty>=3) continue;
            tmp.wz=tx*3+ty;
            for(int j=0; j<9; j++)
                tmp.num[j]=now.num[j];
            swap(tmp.num[tmp.wz],tmp.num[now.wz]);
            tmp.kt=KT(tmp.num);
            if(vis[tmp.kt] || !ok(tmp.num)) continue;
            vis[tmp.kt]=1;
            tmp.step=now.step+1;
            path[tmp.kt]=i;
            pre[tmp.kt]=now.kt;
            tmp.has=hash_(tmp.num);
            Q.push(tmp);
        }
    }
    cout<<"unsolvable"<<endl;
    return ;
}

int main()
{
    memset(vis,0,sizeof(vis));
    node now;
    char s;
    for(int i=0; i<9; i++)
    {
        cin>>s;
        if(s=='x')
        {
            now.num[i]=9;
            now.wz=i;
        }
        else now.num[i]=s-'0';
    }
    if(!ok(now.num))
    {
        cout<<"unsolvable"<<endl;
        return 0;
    }
    now.step=0;
    now.kt=KT(now.num);
    vis[now.kt]=1;
    now.has=hash_(now.num);
    bfs(now);
    return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/we1215053460/article/details/79962111

HDU 1043 ,POJ 1077 Eight

一、数据如何存储和表示? 1、可以用整形来表示八数码的状态,x可以当作“9”,“0”不好处理,例如终态12345678x,可以表示成整数123456789, 2、用数组来存储,这里x可以用0或9来表示...
  • starcuan
  • starcuan
  • 2014-02-06 17:00:11
  • 1098

hdu 1034 & poj 1077 Eight 传说中的八数码问题。真是一道神题,A*算法+康托展开

Problem Description The 15-puzzle has been around for over 100 years; even if you don't know it by t...
  • Lionel_D
  • Lionel_D
  • 2015-02-15 00:04:49
  • 3711

POJ 1077 八数码 三种解法

POJ 1077 Eight题目链接:http://poj.org/problem?id=1077
  • lvxin1204
  • lvxin1204
  • 2016-05-31 13:41:40
  • 1575

POJ 1077 解题报告

这道题我是用bfs+hash做的,最好的方法应该是双向bfs或是A*。虽然这学期刚学的AI,但是偷懒,就这样过了吧。 POJ不支持unordered_map,所以得自己写hash,好在比较简单。由于...
  • thestoryofsnow
  • thestoryofsnow
  • 2014-12-13 05:30:45
  • 378

poj1077解题报告详解

在详细的讲解了一下康拓展开和A*搜索后,我们终于迎来了对八数码问题的致命一击,那这里我就秉承之前的解题报告流程,一不要怪我官方啊;; 1.题意: 此题是一个经典的老提,就是给出一个方阵,你...
  • lovewangtaotao
  • lovewangtaotao
  • 2015-03-09 13:58:51
  • 434

poj-1077 八数码 【a*】

状态总数是9! = 362880 种,不算太多,可以满足广搜和A*对于空间的需求。 假如把x看做0。最大为876543210没超过Int的存储范围,所以用一个int值来表示其平面状态。  #inclu...
  • a915800048
  • a915800048
  • 2015-08-22 10:27:17
  • 371

POJ1077(经典的八数码问题)

很经典的八数码问题,可以用单向广度优先搜索、双向广度优先搜索、A*算法、IDA算法解。 用了双向广度优先搜索和A*算法解,在用A*算法时,纠结了好几天,后来在网上看了一份博客才发现自己错在哪。之后解...
  • sky1203850702
  • sky1203850702
  • 2012-08-05 11:00:49
  • 2885

【启发式搜索】[POJ 1077]Eight

八数码问题,用的A*解决,但是数据太强A不了。。。TLE只能在POJ上先过一发了。#include #include #include #include #include #include ...
  • JeremyGJY
  • JeremyGJY
  • 2015-07-23 15:58:22
  • 456

POJ 1077 Eight, 八数码问题

题目链接: http://poj.org/problem?id=1077 题目类型: 隐式图搜索 原题: The 15-puzzle has been around...
  • shuangde800
  • shuangde800
  • 2012-07-25 00:29:34
  • 2356
收藏助手
不良信息举报
您举报文章:Eight POJ - 1077
举报原因:
原因补充:

(最多只允许输入30个字)