题意:给出了3*3的棋盘,有一个是空白的表示为0,其他地方都填了1到8互不相同的棋子,可以让与空白位置相邻的上下左右的棋子移动到空白位置,要求输出棋子能移动到和初始位置状态最不同的样子和移动步骤。
题解:bfs,用一个结构体存每种棋盘状态,移动步数和移动步骤,每次移动后并且不重复,在加入队列之前,对比当前步数和之前的,步数大的更新结果中的棋盘状态和步骤。
#include <stdio.h>
#include <string.h>
#include <cmath>
#include <algorithm>
#include <map>
#include <queue>
#include <string>
#include <iostream>
using namespace std;
const int N = 3;
struct ST {
int ch[N][N];
int x, y, step;
string str;
}st, st1;
queue<ST> q;
map<long long, int> m;
int init[N][N], ans, res[N][N];
string str1;
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
const char dir[] = {'U', 'D', 'L', 'R'};
int hash(ST temp) {
long long cnt, k;
cnt = k = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
cnt += temp.ch[i][j] * pow(9, k++);
if (!m[cnt]) {
m[cnt] = 1;
return 1;
}
return 0;
}
void bfs() {
q.push(st);
while (!q.empty()) {
st = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int x1 = st.x + dx[i];
int y1 = st.y + dy[i];
if (x1 < 0 || x1 >= N || y1 < 0 || y1 >= N)
continue;
st1 = st;
st1.ch[st1.x][st1.y] = st1.ch[x1][y1];
st1.ch[x1][y1] = 0;
st1.x = x1;
st1.y = y1;
st1.str += dir[i];
if (hash(st1)) {
st1.step += 1;
if (st1.step > ans) {
ans = st1.step;
memcpy(res, st1.ch, sizeof(res));
str1 = st1.str;
}
q.push(st1);
}
}
}
}
int main() {
int t, k = 1;
scanf("%d", &t);
while (t--) {
ans = 0;
m.clear();
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
scanf("%d", &st.ch[i][j]);
if (st.ch[i][j] == 0) {
st.x = i;
st.y = j;
}
}
st.step = 0;
st.str = "";
hash(st);
bfs();
printf("Puzzle #%d\n", k++);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N - 1; j++)
printf("%d ", res[i][j]);
printf("%d\n", res[i][N - 1]);
}
cout << str1 << endl;
printf("\n");
}
return 0;
}