入门经典-p133-八数码问题

#include<cstdio>
#include<cstring>
#include<set>
using namespace std;

typedef int State[9];//定义一个"状态"类型,其是一个长度为9的int型数组 
const int MAXSTATE = 1000000;//状态可能情况一共最大有9!个小于1000000 
State st[MAXSTATE], goal; 
int dist[MAXSTATE];

set<int> vis;
void init_lookup_table() { vis.clear(); }//初始化查找集合 
int try_to_insert(int s) {//插入查找集合 
  int v = 0;
  for(int i = 0; i < 9; i++) v = v * 10 + st[s][i];
  if(vis.count(v)) return 0;
  vis.insert(v);
  return 1;
}

const int dx[] = {-1, 1, 0, 0};//四个方向 
const int dy[] = {0, 0, -1, 1}; 
int bfs() {
  init_lookup_table();
  int front = 1, rear = 2;
  while(front < rear) {
    State& s = st[front];
    if(memcmp(goal, s, sizeof(s)) == 0) return front;//如果已经符合目标局面立即返回 
    int z;
    for(z = 0; z < 9; z++) if(!s[z]) break;//找到0也就是空格的位置 
    int x = z/3, y = z%3;//取对应的列和行,折合算一下 
    for(int d = 0; d < 4; d++) {//四个方向 
      int newx = x + dx[d];
      int newy = y + dy[d];
      int newz = newx * 3 + newy; //倒算回一行的下标 
      if(newx >= 0 && newx < 3 && newy >= 0 && newy < 3) {
        State& t = st[rear];//引用 
        memcpy(&t, &s, sizeof(s));//复制一下然后记录移动后的局面 
        t[newz] = s[z];
        t[z] = s[newz];
        dist[rear] = dist[front] + 1;//此移动步数加在前一个基础上加1 
        if(try_to_insert(rear)) rear++;//看看此前是否重复过此局面,如果是就不再是新的局面 
      }
    }
    front++;//扩展完毕后修改头指针 
  }
  return 0;//返回。 
}

int main() {
  for(int i = 0; i < 9; i++)
    scanf("%d", &st[1][i]);
  for(int i = 0; i < 9; i++)
    scanf("%d", &goal[i]);
  int ans = bfs();
  if(ans > 0) printf("%d\n", dist[ans]);
  else printf("-1\n");
  return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值