A*算法解决八数码问题(C++版本)

八数码问题定义:

八数码问题也称为九宫问题。在3×3的棋盘,摆有八个棋子,每个棋子上标有1至8的某一数字,不同棋子上标的数字不相同。棋盘上还有一个空格,与空格相邻的棋子可以移到空格中。要求解决的问题是:给出一个初始状态和一个目标状态,找出一种从初始转变成目标状态的移动棋子步数最少的移动步骤。


A*算法的通用伪代码 :

AstarwithTree

A*算法解决八数码问题的关键之处:

key
关键之处:
要维护两个结构:

  • open表,存放将要拓展的节点。
  • close表,存放已经拓展过的节点。

每次从open表中选择F值(f = g + h)最小的点进行拓展,对于拓展出的新节点要,如果已经访问过且此时F值比以前访问时更优时,要更新close表,并将此节点重新插入到open表中。


实现源代码:

#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <list>
//#include "process.cpp";
#define SIZE 3//棋盘的大小 size*size

using namespace std;

/**
 *定义方案节点
 */
typedef struct Node
{
  vector<int> board;
  int rc;
  int h;
  int g;
  int parent;//在close中指示父亲节点的下表

}pNode;

int x_axis[] = {-1,  0, 0, 1};
int y_axis[] = { 0, -1, 1, 0};

/**
 *输出方案
 */
void print(vector<int> board, int rc)
{
  cout<<"当前方案为:"<<endl;
  for(int i = 0; i < rc; ++i)
  {
    for(int j = 0; j < rc; ++j)
    {
      cout<<board[i*rc+j]<<' ';
    }
    cout<<endl;
  }
  //cout<<"当前方案的F值为:"<<endl;
  //cout<<board[board.size()-1]<<endl;

  return ;
}

/**
 *将遍历到的当前节点输出到文本文件中
 */
void out_data(pNode &node)
{
  int s = node.rc;
  ofstream outdata("rt.txt",ios::app);

  outdata<<"第"<<node.parent<<"层数据"<<endl;
  for(int i = 0; i < s; i++) {
    for(int j = 0; j < s; j++) {
      outdata<<node.board[i*s+j]<<" ";
    }
    outdata<<endl;
  }
  outdata<<"h值:"<<node.h<<endl;

  outdata.flush();
  outdata.close();
  return ;
}
/*
 *判断棋盘是否有序
 *
 *@param vector<int> board
 *@return bool是否有序
 */
bool is_ordered(vector<int> board)
{
  for(int i = 0; i < board.size(); ++i)
  {
    if(board[i] != i)
      {
        return false;
      }
  }
  return true;
}

/**
 *定义heuristic函数 探索函数
 *
 *@param vector<int> board , int rc 表示解决方案是rc*rc的 r&c 
 *@return int value of heuristic
 */
int heuristics(vector<int> board,int rc)
{
  //表示元素的正确位置
  int gx = 0;
  int gy = 0;

  //表示Manhattan block distance
  int distance = 0;

  for(int i = 0; i < rc*rc; ++i)
  {
    int nx = i / rc;
    int ny = i % rc;

    gx = board[i] / rc;
    gy = board[i] % rc;

    distance += abs(nx - gx) + abs(ny-gy);
  }
  return distance;
}

/**
 *same_plan()判断两个vector<int> 是否相等
 *即判断两个方案是否相等
 *
 *@param vector<int> board1, vector<int> board2
 *@return bool
 */
bool same_plan(vector<int> board1, vector<int> board2)
{
  //首先判断数组的长度是否相等
  if(board1.size() != board2.size())
  {
    return false;
  }

  //判断每一个元素是否对应相等
  for(int i = 0; i < board1.size(); ++i)
  {
    if(board1[i] != board2[i])
    {
      return false;
    }
  }
  //所有元素都比较完毕以后
  return true;
}

/**
 *In_open()函数,判断一个节点是否在open表中
 *
 *@param pNode, list<pNode> open
 *@return bool true--在ope表中, false--不再open表中
 */
bool in_open(pNode plan, list<pNode> &open)
{
  //遍历整个open表,使用迭代器
  for(list<pNode>::iterator it = open.begin(); it != open.end(); it++)
  {
    if(same_plan(plan.board, (*it).board))
    {
      return true;
    }
  }
  return false;
}

/**
 *in_close()函数,判断一个节点是否在close表中
 *
 *@param pNode, vector<pNode> close
 *@return bool true 在close表中 false不再表中
 */
bool in_close(pNode plan, vector<pNode> &close)
{
  //遍历每一个节点
  for(int i = 0; i < close.size(); i++)
  {
    if(same_plan(plan.board, close[i].board))
    {
      return true;
    }
  }
  //都遍历完毕以后依然没有找到
  return false;
} 

/**
 *insert_close()函数 将正在访问的节点添加到close表中
 *
 *@param pNode, vector<pNode &close
 *@return int position ,节点在close表中的索引
 */
int insert_close(pNode plan, vector<pNode>& close)
{
  close.push_back(plan);

  return close.size()-1;
}

/**
 *insert_open()函数 将新生成的plan添加到fringe上去
 *
 *@param pNode plan, list<pNode> fringe
 *@return  fringe
 */
bool insert_open(pNode plan, list<pNode>& open)
{
  //先取得当前方案的f-value值 = h + g;
  int f = plan.h + plan.g;
  //int h = plan.h;

  //遍历fringe,查看此方案是否已在队列中
  for(list<pNode>::iterator it = open.begin(); it != open.end(); it++)
  {
    //if(h < ((*it).f + (*it).g))
    if(f < ((*it).h+(*it).g))
    {
      //cout<<"进行插入"<<endl;
      open.insert(it, plan);

      return true;
    }
  }
  //当走到这时,说明这个plan的fvalue是最大的
  open.push_back(plan);

  return true;
}

/**
 *generate函数:生成新的解决方案
 *
 *@param vector<int> board, list<board> l, int rc边的长度;
 */
void generate(list<pNode>& open, vector<pNode> &close)
{
  //取得h值最小的元素
  pNode plan = open.front();

  //将取得的节点从open包中删除
  open.pop_front();

  //将当前方案添加到close表中
  int pos = insert_close(plan, close);
  //数据是3*3的
  int rc = plan.rc;

  //寻找0的位置
  int px;
  int py;

  for(int i = 0; i < rc*rc; ++i)
  {
    if(plan.board[i] == 0)
    {
      px = i / rc;
      py = i % rc;
    }
  }
  //想四个方向拓展,首先得判断能否拓展
  for(int i = 0; i < 4; i++)
  {
    if(px+x_axis[i] >= 0 && px+x_axis[i] < rc &&
       py+y_axis[i] >= 0 && py+y_axis[i] < rc)
    {
      //生成一个新的节点
      pNode new_plan = plan;
      new_plan.board[px*rc+py] =
        new_plan.board[(px+x_axis[i])*rc+(py+y_axis[i])];
      new_plan.board[(px+x_axis[i])*rc+(py+y_axis[i])] = 0;

      new_plan.h = heuristics(new_plan.board, new_plan.rc);
      new_plan.g = plan.g+1;//g表示层数
      new_plan.parent = pos;//记录新生成节点的父节点

      if(in_open(new_plan, open))//如果新生成的节点在open表中
      {
        for(list<pNode>::iterator it = open.begin(); it != open.end(); it++)
        {
          if(same_plan(new_plan.board, (*it).board))
          {
            if((new_plan.h+new_plan.g) > ((*it).h+(*it).g))
            {
              //open.erase(it);
              break;
            }
            else
            {
              //删除
              open.erase(it);
              break;
            }
          }
          //找该节点应该插入的位置
          bool inserted = false;
          if(!inserted && (new_plan.h+new_plan.g) < ((*it).h+(*it).g))
          {
            inserted = true;
            open.insert(it, new_plan);
          }
        }
      }
      else if(in_close(new_plan, close))
      {
        for(int i = 0; i < close.size(); i++)
        {
          if(same_plan(new_plan.board, close[i].board) &&
             ((new_plan.h+new_plan.g)<(close[i].h+close[i].g)))
           {
             close[i].h = new_plan.h;
             close[i].g = new_plan.g;
             //将这个重新赋值的节点插入到open表中
             insert_open(new_plan, open);
             break;
           }
        }
      }
      else
      {
        insert_open(new_plan, open);
      }
    }
  }
  return ;
}

/**
 *void get_path()函数,根据当前符合目标状态的节点在close表中回溯,
 * 从而获得从起点到达目标终点的路径
 *
 *@param pNode, vector<pNode> close
 *@return null
 */
void get_path(pNode plan, vector<pNode> &close, int plen)
{
  if(plan.parent == -1)
  {
    print(plan.board, plan.rc);

    cout<<"路径长度为:"<<plen++<<endl;
    return;//递归出口,表示回溯到起点
  }
  //输出当前节点
  print(plan.board, plan.rc);

  return get_path(close[plan.parent], close, ++plen);
}

int main(int argc, char *argv[])
{
  //构造输入
  pNode plan;

  //生成初始状态
  ifstream data_in("input.txt");
  char digit;

  while(data_in.get(digit))
  {
    if(digit >= '0' && digit <= '9')
    {
      int num = digit - '0';
      //cout<<digit;
      plan.board.push_back(num);
    }
  }

  plan.rc = 3;
  plan.g = 1;
  plan.parent = -1; //标识起点

  plan.h = heuristics(plan.board, plan.rc);

  //生成open表,并将起点添加到表中
  list<pNode> open;
  open.push_back(plan);

  //生成close表
  vector<pNode> close;

  while(!open.empty())
  {
    //print(open.front().board, 3);
    out_data(open.front());
    //判断当前节点是否满足目标状态
    if(is_ordered(open.front().board))
    {
      cout<<"************************"<<endl;
      cout<<"*******查找完成*********"<<endl;
      cout<<"************************"<<endl;
      get_path(open.front(), close, 0);
      break;
    }
    //产生新的方案
    generate(open, close);
  }
  //cout<<close.size()<<endl;
  return 0;
}

测试用例

[1 6 4 8 7 0 3 2 5]的输入可以得到21步的最优解。

  • 15
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 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在两个状态中的偏移距离。
以下是使用A*算法解决八数码问题C++代码示例: ```c++ #include <iostream> #include <cstdio> #include <cstring> #include <queue> #include <algorithm> using namespace std; const int MAXN = 1e5 + 5; const int INF = 0x3f3f3f3f; int dx[4] = {0, 0, 1, -1}; int dy[4] = {1, -1, 0, 0}; struct node { int x, y, step, f; int a[3][3]; bool operator < (const node &rhs) const { return f > rhs.f; } }; int n, m, sx, sy, ex, ey; int vis[MAXN], ans[MAXN]; node st, ed; int get_h(node a, node b) { int res = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (a.a[i][j] == 0) continue; for (int k = 0; k < 3; k++) { for (int l = 0; l < 3; l++) { if (a.a[i][j] == b.a[k][l]) { res += abs(i - k) + abs(j - l); } } } } } return res; } bool check(node a) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (a.a[i][j] != ed.a[i][j]) { return false; } } } return true; } void A_star() { priority_queue<node> q; st.f = get_h(st, ed); q.push(st); while (!q.empty()) { node u = q.top(); q.pop(); if (check(u)) { printf("%d\n", u.step); return; } for (int i = 0; i < 4; i++) { int nx = u.x + dx[i]; int ny = u.y + dy[i]; if (nx < 0 || nx >= 3 || ny < 0 || ny >= 3) continue; node v = u; swap(v.a[u.x][u.y], v.a[nx][ny]); v.x = nx, v.y = ny; v.step++; v.f = v.step + get_h(v, ed); if (vis[v.a[0][0] * 1000000 + v.a[0][1] * 100000 + v.a[0][2] * 10000 + v.a[1][0] * 1000 + v.a[1][1] * 100 + v.a[1][2] * 10 + v.a[2][0]] == 0) { vis[v.a[0][0] * 1000000 + v.a[0][1] * 100000 + v.a[0][2] * 10000 + v.a[1][0] * 1000 + v.a[1][1] * 100 + v.a[1][2] * 10 + v.a[2][0]] = 1; q.push(v); } } } } int main() { scanf("%d%d", &sx, &sy); st.x = sx, st.y = sy; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { scanf("%d", &st.a[i][j]); } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { scanf("%d", &ed.a[i][j]); } } A_star(); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值