A*算法解决八数码问题


#include <iostream>
#include <cstring>
#include <vector>
#include <cmath>
#include <conio.h>
#include <cstdlib>
#include <algorithm>
#include <windows.h>
using namespace std;

#define DIRECTION int

const char TEST_END        = '0';
const int BOARDSIZE        = 3;
const int TABLESIZE        = 370000;
const int DIRECTION_SIZE   = 4;
const int INIT_POS_IN_HASH = -1;
const int INIT_PARENT      = -1;
const int INIT_START       = -1;
const int INIT_G           = 1;
const int G_GROW           = 1;
const char BLANK           = 'X';

enum VISITESTATE{ NOTFOUND, INOPEN, INCLOSE };
const int hashArr[9]            = { 7, 17, 47, 117, 217, 977, 1299, 5971, 7779 };
const int dir_x[DIRECTION_SIZE] = { -1, 1, 0, 0 };
const int dir_y[DIRECTION_SIZE] = { 0, 0, -1, 1 };      //Up Down Left Right


struct position{
    
    position(){}
    position( int xx, int yy ):x( xx ), y( yy ){}
    
    int x;
    int y;
    
};


position finalPosition[BOARDSIZE * BOARDSIZE];


struct ChessBoard{
    
    ChessBoard(){
        
        visitState     = NOTFOUND;
        posInHashTable = INIT_POS_IN_HASH;
        
    }
    
    ChessBoard& operator = ( const ChessBoard& cb ){
        
        for( int i = 0; i < BOARDSIZE; ++i ){
            for( int j = 0; j < BOARDSIZE; ++j ){
                this->ChessState[i][j] = cb.ChessState[i][j];
            }
        }
        
        this->blankX         = cb.blankX;
        this->blankY         = cb.blankY;
        this->g              = cb.g;
        this->h              = cb.h;
        this->direction      = cb.direction;
        this->parent         = cb.parent;
        this->posInHashTable = cb.posInHashTable;
        
        return *this;
        
    }
    
    friend bool operator < ( const ChessBoard& a, const ChessBoard& b ){
        return ( a.g + a.h ) > ( b.g + b.h );
    }
    
    
    char ChessState[BOARDSIZE][BOARDSIZE];
    
    VISITESTATE visitState;
    int blankX;
    int blankY;
    int g;
    int h;
    int direction;
    int posInHashTable;
    int parent;
    
};


ChessBoard hashTable[TABLESIZE];


class AStarAlg{
    
    public:
    
        AStarAlg(){
            
            finalState.ChessState = {
                { '1', '2', '3' },
                { '4', '5', '6' },
                { '7', '8', BLANK }
            };
            
            initChessBoard();
            
        }
        
        void initChessBoard();
        void AStar();
        void printPath( ChessBoard );
        void showChessBoard( const ChessBoard& ) const;
        
        const ChessBoard& getChessBoard( int index ){ return hashTable[index]; };
        const ChessBoard& getInitalChessBoard(){ return initState; };
        
    private:
    
        bool isSolvable( const ChessBoard& );
        bool getNextChessBoard( ChessBoard& nextState, const ChessBoard& parentState, const DIRECTION& );
        int hashCal( ChessBoard& );
        void setInOpen( ChessBoard& );
        void updateOpen( const ChessBoard& );
        bool isInOpen( const ChessBoard& ) const;
        void setInClose( ChessBoard& );
        bool isNotFound( const ChessBoard& ) const;
        bool isInClose( const ChessBoard& ) const;
        void calHeuristic( ChessBoard& );
        void calG( ChessBoard& );
        void calFun( ChessBoard& );
        bool isEqual( const ChessBoard&, const ChessBoard& );

        vector< ChessBoard >openTable;
        
        ChessBoard initState;
        ChessBoard finalState;
        
};


bool AStarAlg::isSolvable( const ChessBoard& cb ){
    
    char* tempArr    = new char[BOARDSIZE * BOARDSIZE + 1];
    const int length = BOARDSIZE * BOARDSIZE;
    int count        = 0;
    int countNum     = 0;
    
    for( int i = 0; i < BOARDSIZE; ++i ){
        for( int j = 0; j < BOARDSIZE; ++j ){
            
            if( initState.ChessState[i][j] == BLANK ) 
                tempArr[count] = '9';
            else 
                tempArr[count] = initState.ChessState[i][j];
                
            count++;
            
        }
    }
    
    for( int i = 0; i < length; ++i ){
        
        const int base = tempArr[i] - '0';
        
        for( int j = 0; j < i; ++j ){
            
            const int cmp = tempArr[j] - '0';
            
            if( cmp > base )
                countNum++;
            
        }
    }
    
    delete tempArr;
    
    if( countNum % 2 != 0 ) 
        return false;
        
    return true;
}


void AStarAlg::setInOpen( ChessBoard& cb ){
    
    cb.visitState                           = INOPEN;
    hashTable[cb.posInHashTable].visitState = INOPEN;
    
    openTable.push_back( cb );
    push_heap( openTable.begin(), openTable.end() );
    
}


void AStarAlg::printPath( ChessBoard cb ){
    
    if( cb.parent == INIT_PARENT ){
        
        cout<<"Finsh."<<endl;
        return;
        
    }
    
    vector< ChessBoard >path;
    
    while( true ){
        
        path.push_back( cb );
        if( cb.parent == INIT_PARENT )
            break;
        cb = hashTable[cb.parent];
        
    }
    
    for( int i = path.size() - 1; i >= 0; --i ){
        showChessBoard( path[i] );
    }
}


void AStarAlg::updateOpen( const ChessBoard& cb ){
    
    for( int i = 0; i < openTable.size(); ++i ){
        if( isEqual( openTable[i], cb ) ){
            
            openTable[i] = cb;
            break;
            
        }
    }
    
    make_heap( openTable.begin(), openTable.end() );
    
}


void AStarAlg::setInClose( ChessBoard& cb ){
    
    hashTable[cb.posInHashTable].visitState = INCLOSE;
    cb.visitState                           = INCLOSE;
    
}


bool AStarAlg::isInClose( const ChessBoard& cb ) const{
    return ( hashTable[cb.posInHashTable].visitState == INCLOSE ) ? true : false;
}


bool AStarAlg::isInOpen( const ChessBoard& cb ) const{
    return ( hashTable[cb.posInHashTable].visitState == INOPEN ) ? true : false;
}


bool AStarAlg::isNotFound( const ChessBoard& cb ) const{
    return ( hashTable[cb.posInHashTable].visitState == NOTFOUND ) ? true : false;
}


void AStarAlg::calHeuristic( ChessBoard& cb ){
    
    int h = 0;
    
    for( int i = 0; i < BOARDSIZE; ++i ){
        for( int j = 0; j < BOARDSIZE; ++j ){
            
            int val = cb.ChessState[i][j] - '0';
            int x   = finalPosition[val - 1].x;
            int y   = finalPosition[val - 1].y;
            h       += abs( i - x ) + abs( j - y );
            
        }
    }
    
    cb.h = h;
    
}


void AStarAlg::calG( ChessBoard& cb ){
    
    if( cb.parent == INIT_PARENT )
        cb.g = INIT_G;
    else
        cb.g = hashTable[cb.parent].g + G_GROW;
    
}


void AStarAlg::calFun( ChessBoard& cb ){
    
    calHeuristic( cb );
    calG( cb );
    
}


void AStarAlg::initChessBoard(){
    
    string str;
    
    cout << "Enter inital State : ";
    getline( cin, str );
    
    int count = 0;
    
    for( int i = 0; i < str.length(); ++i ){
        if( str[i] != ' ' ){
            
            initState.ChessState[count / BOARDSIZE][count % BOARDSIZE] = str[i];
            
            if( str[i] == 'x' ){
                
                initState.ChessState[count / BOARDSIZE][count % BOARDSIZE] = BLANK;
                initState.blankX = count / BOARDSIZE;
                initState.blankY = count % BOARDSIZE;
                
            }
            
            ++count;
            
        }
    }
    
    initState.direction = INIT_START;
    initState.parent    = INIT_PARENT;
    calFun( initState );
    int pos = hashCal( initState );
    openTable.push_back( initState );
    make_heap( openTable.begin(), openTable.end() );
    
}


bool AStarAlg::isEqual( const ChessBoard& cbA, const ChessBoard& cbB ){
    
    for( int i = 0; i < BOARDSIZE; ++i ){
        for( int j = 0; j < BOARDSIZE; ++j ){
            if( cbA.ChessState[i][j] != cbB.ChessState[i][j] ) 
                return false;
        }
    }
    
    return true;
    
}


int AStarAlg::hashCal( ChessBoard& cb ){
    
    /*  function: calculate the position of the state of chessboard in hashTable
        if the state has been existing ( INOPEN , INCLOSE ) then return its position is hashTble
        else set the state in hashTable and then return its position
        PS: must after all operation ( my drawback ) */
    
    int pos = 0;
    
    for( int i = 0; i < BOARDSIZE; ++i ){
        for( int j = 0; j < BOARDSIZE; ++j ){
    
            int val = cb.ChessState[i][j] - '0';
            pos     += val * hashArr[ BOARDSIZE * i + j ];
            
        }
    }
    
    pos = pos % TABLESIZE;
    
    while( hashTable[pos].visitState != NOTFOUND ){
        
        if( isEqual( hashTable[pos], cb ) ){
            
            cb.posInHashTable = pos;
            
            return pos;
            
        }
        
        pos = ( pos + 1 ) % TABLESIZE;
        
    }
    
    cb.posInHashTable = pos;
    hashTable[pos]    = cb;
    
    return pos;
    
}


bool AStarAlg::getNextChessBoard( ChessBoard& tempNextState,
                                  const ChessBoard& parentState,
                                  const DIRECTION& dir ){
    //Get temp next chess board blank_x and blank_y
    int tempNextBlankX = parentState.blankX + dir_x[dir];
    int tempNextBlankY = parentState.blankY + dir_y[dir];
    
    if( tempNextBlankX < 0 || tempNextBlankX > BOARDSIZE - 1
        || tempNextBlankY < 0 || tempNextBlankY > BOARDSIZE - 1 ) 
        return false;

    tempNextState.blankX    = tempNextBlankX;
    tempNextState.blankY    = tempNextBlankY;
    tempNextState.direction = dir;
    
    //Get temp next chess board state
    for( int i = 0; i < BOARDSIZE; ++i ){
        for( int j = 0; j < BOARDSIZE; ++j ){
            tempNextState.ChessState[i][j] = parentState.ChessState[i][j];
        }
    }
    
    char change = tempNextState.ChessState[tempNextState.blankX][tempNextState.blankY];
    tempNextState.ChessState[parentState.blankX][parentState.blankY]     = change;
    tempNextState.ChessState[tempNextState.blankX][tempNextState.blankY] = BLANK;
    
    //Get temp next chess board parent position
    tempNextState.parent = parentState.posInHashTable;
    
    //Get temp next chess board g and h, its parent state has got
    calFun( tempNextState );
    
    //Hash Cal
    hashCal( tempNextState );
    
    return true;
    
}


void AStarAlg::AStar(){
    
    char c;
    
    while( !openTable.empty() ){
        
        pop_heap( openTable.begin(), openTable.end() );
        ChessBoard parent = openTable.back();
        
        if( !isSolvable( parent ) ){
            
            cout<<"unsolvable"<<endl;
            
            return;
            
        }
        
        openTable.erase( openTable.end() - 1 );
        setInClose( parent );

        if( isEqual( parent, finalState ) ){
            
            printPath( parent );
            
            return;
            
        }
        
        for( int i = 0; i < DIRECTION_SIZE; ++i ){
            
            ChessBoard tempNextState;
            
            if( !getNextChessBoard( tempNextState, parent, i ) )
                continue;
                
            if( isNotFound( tempNextState ) ){
                
                setInOpen( tempNextState );
                
                continue;
                
            }
            
            if( isInOpen( tempNextState ) ){
                
                int f = tempNextState.g + tempNextState.h;
                
                if( f < hashTable[tempNextState.posInHashTable].g + hashTable[tempNextState.posInHashTable].h ){
                    
                    hashTable[tempNextState.posInHashTable] = tempNextState;
                    updateOpen( tempNextState );
                    
                    continue;
                }
            }
            
            if( isInClose( tempNextState ) ){
                
                int f = tempNextState.g + tempNextState.h;
                
                if( f < hashTable[tempNextState.posInHashTable].g + hashTable[tempNextState.posInHashTable].h ){
                    
                    hashTable[tempNextState.posInHashTable] = tempNextState;
                    setInOpen( tempNextState );
                    
                    continue;
                }
            }
        }
    }
    
    cout << "unsolveable" << endl;
    
}


void AStarAlg::showChessBoard( const ChessBoard& cb ) const{
    
    cout << endl;
    cout << "<<<<<<<<<<<<<<<<<<<<<< Pandora >>>>>>>>>>>>>>>>>>>>>" << endl;
    cout << "ChessBoard State : " << endl;
    
    for( int i = 0; i < BOARDSIZE; ++i ){
        
        for( int j = 0; j < BOARDSIZE; ++j )
            cout<<cb.ChessState[i][j]<<"  ";
            
        cout<<endl;
        
    }
    
    cout << "Blank_X : " << cb.blankX << "    " << "Blank_Y : " << cb.blankY << endl;
    cout << "Position is HashTable : " << cb.posInHashTable << endl;
    cout << "Parent : " << cb.parent << endl;
    cout << "G : " << cb.g << "   " << "H : " << cb.h << "   " << "F : " << cb.h + cb.g << endl;
    
    switch( cb.visitState ){
        
        case NOTFOUND:{
            
            cout << "Now my state : Not be found." << endl;
            break;
            
        }
        case INOPEN:{
            
            cout << "Now my state : In open table." << endl;
            break;
            
        }
        case INCLOSE:{
            
            cout << "Now my state : In close" << endl;
            break;
            
        }
        default:{
            
            cout << "Error state!" << endl;
            break;
            
        }
    }
    
    cout << "<<<<<<<<<<<<<<<<<<<<<< Pandora >>>>>>>>>>>>>>>>>>>>>" << '\n\n';
}


void preWork(){
    
    int count = 0;
    
    for( int i = 0; i < BOARDSIZE; ++i ){
        for( int j = 0; j < BOARDSIZE; ++j ){
            
            position temp;
            temp.x = i;
            temp.y = j;
            finalPosition[count] = temp;
            count++;
            
        }
    }
}


int main(){
    
    AStarAlg a;
    
    preWork();
    a.AStar();
    
    return 0;
    
}


A*算法求解八数码问题 1、A*算法基本思想: 1)建立一个队列,计算初始结点的估价函数f,并将初始结点入队,设置队列头和尾指针。 2)取出队列头(队列头指针所指)的结点,如果该结点是目标结点,则输出路径,程序结束。否则对结点进行扩展。 3)检查扩展出的新结点是否与队列中的结点重复,若与不能再扩展的结点重复(位于队列头指针之前),则将它抛弃;若新结点与待扩展的结点重复(位于队列头指针之后),则比较两个结点的估价函数中g的大小,保留较小g值的结点。跳至第五步。 4)如果扩展出的新结点与队列中的结点不重复,则按照它的估价函数f大小将它插入队列中的头结点后待扩展结点的适当位置,使它们按从小到大的顺序排列,最后更新队列尾指针。 5)如果队列头的结点还可以扩展,直接返回第二步。否则将队列头指针指向下一结点,再返回第二步。 2、程序运行基本环境: 源程序所使用编程语言:C# 编译环境:VS2010,.net framework 4.0 运行环境:.net framework 4.0 3、程序运行界面 可使用程序中的test来随机生成源状态与目标状态 此停顿过程中按Enter即可使程序开始运行W(n)部分; 此停顿部分按Enter后程序退出; 4、无解问题运行情况 这里源程序中是先计算源状态与目标状态的逆序对的奇偶性是否一致来判断是否有解的。下面是无解时的运行画面: 输入无解的一组源状态到目标状态,例如: 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 8 7 0 运行画面如下: 5、性能比较 对于任一给定可解初始状态,状态空间有9!/2=181440个状态;当采用不在位棋子数作为启发函数时,深度超过20时,算法求解速度较慢; 其中启发函数P(n)与W(n)的含义如下: P(n): 任意节点与目标结点之间的距离; W(n): 不在位的将牌数; 源状态 目标状态 P(n) 生成节点数 W(n) 生成节点数 P(n) 扩展节点数 W(n) 扩展节点数 2 8 3 1 6 4 7 0 5 1 2 3 8 0 4 7 6 5 11 13 5 6 1 2 3 8 0 4 7 6 5 0 1 3 8 2 4 7 6 5 6 6 2 2 4 8 2 5 1 6 7 0 3 7 4 2 8 5 6 1 3 0 41 79 22 46 6 2 5 8 7 0 3 1 4 0 3 6 7 1 8 4 5 2 359 10530 220 6769 7 6 3 1 0 4 8 5 2 2 8 7 1 3 4 6 5 0 486 8138 312 5295 下图是解决随机生成的100中状态中,P(n)生成函数的生成节点与扩展节点统计图: 由上图可知,P(n)作为启发函数,平均生成节点数大约在1000左右,平均扩展节点数大约在600左右; 下图是解决随机生成的100中状态中,W(n)生成函数的生成节点与扩展节点统计图: 由上图可知,W (n)作为启发函数,平均生成节点数大约在15000左右,是P(n)作为启发函数时的平均生成节点的15倍;W (n)作为启发函数,平均扩展节点数大约在10000左右,是P(n)作为启发函数时的平均扩展节点的15倍; 下图是解决随机生成的100中状态中,两个生成函数的生成节点与扩展节点统计图: 由上述图表可以看到,将P(n)作为启发函数比将W(n)作为启发函数时,生成节点数与扩展节点数更稳定,相比较来说,采用P(n)作为启发函数的性能比采用W(n)作为启发函数的性能好。 6、源代码说明 1)AStar-EightDigital-Statistics文件夹:用来随机生成100个状态,并对这100个状态分别用P(n)与W(n)分别作为启发函数算出生成节点以及扩展节点,以供生成图表使用;运行界面如下: 2)Test文件夹:将0-8这9个数字随机排序,用来随机生成源状态以及目标状态的;运行界面如下: 3)AStar-EightDigital文件夹:输入源状态和目标状态,程序搜索出P(n)与W(n)分别作为启发函数时的生成节点数以及扩展节点数,并给出从源状态到目标状态的移动步骤;运行界面如下: 提高了运行速度的几处编码思想: 1、 在维护open以及close列表的同时,也维护一个类型为hashtable的open以及close列表,主要用来提高判断当前节点是否在open列表以及close列表中出现时的性能; 2、 对于每个状态,按照从左到右,从上到下,依次将数字拼接起来,形成一个唯一标识identify,通过该标识,可以直接判断两个状态是否是同一个状态,而不需要循环判断每个位置上的数字是否相等 3、 在生成每个状态的唯一标识identify时,同时计算了该状态的空格所在位置,通过空格所在位置,可以直接判断能否进行上移、下移、左移、右移等动作; 4、 只计算初始节点的h值,其它生成的节点的h值是根据当前状态的h值、移动的操作等计算后得出的,规则如下: a) 采用W(n)这种方式,不在位置的将牌数,共有以下3中情况: i. 该数字原不在最终位置上,移动后,在其最终位置上 这种情况下,生成的子节点的h值= 父节点的h值-1 ii. 该数字原在最终位置上,移动后,不在其最终位置上 这种情况下,生成的子节点的h值= 父节点的h值 +1 iii. 该数字原不在最终位置上,移动后,还是不在其最终位置上 这种情况下,生成的子节点的h值= 父节点的h值 iv. 该数字原在最终位置上,移动后,还在其最终位置 这种情况不存在 b) 采用P(n)这种方式,节点与目标距离,可通过下面3步完成 i. 首先计算在原位置时,与目标位置的距离,命名为Distance1 ii. 移动后,计算当前位置与目标位置的距离,命名为Distance2 iii. 计算子节点的h值: 子节点的h值 = 父节点的h值- Distance1+ Distance2 5、 在任意状态中的每个数字和目标状态中同一数字的相对距离就有9*9种,可以先将这些相对距离算出来,用一个矩阵存储,这样只要知道两个状态中同一个数字的位置,就可查出它们的相对距离,也就是该数字的偏移距离;例如在一个状态中,数字8的位置是3,在另一状态中位置是7,那么从矩阵的3行7列可找到2,它就是8在两个状态中的偏移距离。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值