7.5.3 八数码问题

bfs图的时候需要注意判重。

八数码状态数 9!=362880 ,如果用9维的vis,9^9=387420489,会有很大的浪费。

有三种方法来解决空间浪费问题:

1、编码解码

这里用cantor编码

typedef int State[9];
const int MAXSTATE = 1000000;
State st[MAXSTATE], goal;
int dist[MAXSTATE];

int vis[362880], fact[9];
void init_lookup_table() {
  fact[0] = 1;
  for(int i = 1; i < 9; i++) fact[i] = fact[i-1] * i;
}
int try_to_insert(int s) {
  int code = 0;
  for(int i = 0; i < 9; i++) {
    int cnt = 0;
    for(int j = i+1; j < 9; j++) if(st[s][j] < st[s][i]) cnt++;
    code += fact[8-i] * cnt;
  }
  if(vis[code]) return 0;
  return vis[code] = 1;
}

2、hash

3、STL 的 set

set需要定义 < 运算符

原文地址:https://www.cnblogs.com/cute/p/3685774.html