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
    评论
 站长网站优化时,不是拿到一个网站就去做关键词做外链,第一步应是要去了解网站,制作可 执行的网站优化方案。那要想制作份完善的网站优化方案,最重要的是那几步,方案中应该要包括哪些内容。   第一:分析自身网站。首先要分析自己的网站属于什么类型,网站的主要方向是怎样的,网站的主关键词是什么,还有就是网站优化前的基本数据。从谷歌分析工具中可以看到网站的一些基本数据,记录这些基本的数据,可以清楚的和优化后的网站进行对比,这样才能看出网站优化后到底有没有效果。从而判断我们的网站优化是否成功,这也是站长们想看到的最终结果。   第二:定位对手网站。自身的网站分析完后,并可定出网站的主关键词,主关键词定好后,就是要通过这个关键词找到网站的对手,在搜索引擎输入相应的关键词,找到关键词排名前2页的站点,这些站点都算是你网站的竞争对手。不管竞争对手是首页优化,还是单页优化,你都要加入竞争对手的行列,别人竟然是有排名,肯定是有他做的比较好的地方。   第三:分析竞争对手。竞争对手确定好以后,就是要分享竞争对手的网站。很多站长可能会很迷惑,我做我自己的网站,我分析别人的干嘛。他是你的竞争对手,那你就要从他那找到好的地方,用到自己的网站上,然后去除他不好的,这样你的网站才能比他做的好。分析竞争对手要从以下几个方面进行分析。   首先:分析对手的基本数据。对方网站的首页快照情况,网站的收录,网站的雅虎外链数,网站的域名注册时间等。分析这些数据的同时也要和自己的网站进行对比,看自己的网站和别人的差距在那,不足的地方在日后的优化过程中要改进。   其次:分析对手网站的meta标签。看对手网站的meta标签title属性,看别人是如何部署自己的关键词,关键词的密度是多少。还有就是description属性,虽然蜘蛛不抓取,但是呈现给用户的,这样对用户的选择是很重要的,用户往往会根据网站的描述,选择适合自己的网站。   最后:分析对手网站的不同分类。往往网站优化会利用分类去优化,一级分类页面优化时会给分类添加一段文字描述,80个字符左右,这样可以提高用户的体验,同时也能提高抓取对分类页面的抓取。分类页面最好是能添加上面包屑的导航,这样可以更好的提供用户体验。   第四:给自身网站定优化方案。在第一步的时候我们已经用谷歌的分析工具分析了网站的基本数据,基本数据分析好后,我们能看到网站的基本关键词来源,流量来源,和搜索引擎的一些数据。根据这些数据我们要定制出符合网站优化的方案,如不同的关键词要选择不同的页面去优化,不同页面要有适合的title;网站导航问题要进行面包屑的导航;网站URL是否要简化;用谷歌管理员工具查看网站是否有重复页面,重复元说明等;然后给网站定制合理的外链建设方案。   其实通过以上几步的分析过程,要想给网站定制一个合理的方案基本上是可以了,但实际问题还是要考虑到你网站的可执行,要根据你网站的数据来源,一定要定制可执行的网站方案。
以下是使用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、付费专栏及课程。

余额充值