题意:开9维的BFS,看了别人的优化方法是:用到了优先队列,因为求的最短的操作路径,所以用当前的步数作为优先队列的条件,步数少的优先
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int flag[4][4][4][4][4][4][4][4][4];
int op[10][10] = {{0},{1,2,4,5},{1,2,3},{2,3,5,6},{1,4,7},{2,4,5,6,8},
{3,6,9},{4,5,7,8},{7,8,9},{5,6,8,9}};
int st[10];
struct node{
int state[10];
int pos;
int ans[200];
friend bool operator < (const node &a,const node &b){
return a.pos > b.pos;
}
}s,now;
void bfs(){
priority_queue<node> Q;
memset(flag,0,sizeof(flag));
for (int i = 1; i <= 9; i++)
s.state[i] = st[i];
s.pos = 0;
flag[st[1]][st[2]][st[3]][st[4]][st[5]][st[6]][st[7]][st[8]][st[9]] = 1;
Q.push(s);
while (!Q.empty()){
now = Q.top();
Q.pop();
for (int i = 1; i <= 9; i++){
s = now;
for (int j = 0; op[i][j]; j++)
s.state[op[i][j]] = (s.state[op[i][j]]+1) % 4;
if(!flag[s.state[1]][s.state[2]][s.state[3]][s.state[4]][s.state[5]][s.state[6]][s.state[7]][s.state[8]][s.state[9]]) {
s.ans[s.pos++] = i;
flag[s.state[1]][s.state[2]][s.state[3]][s.state[4]][s.state[5]][s.state[6]][s.state[7]][s.state[8]][s.state[9]] = 1;
Q.push(s);
}
if(!s.state[1] && !s.state[2] && !s.state[3] && !s.state[4] && !s.state[5] && !s.state[6] && !s.state[7] && !s.state[8] && !s.state[9]){
sort(s.ans,s.ans + s.pos);
for(int j = 0; j < s.pos; j++)
printf("%d ",s.ans[j]);
printf("\n");
return;
}
}
}
}
int main(){
int n;
while (scanf("%d",&n) != EOF){
st[1] = n;
for (int i = 2; i <= 9; i++)
scanf("%d",&st[i]);
bfs();
}
return 0;
}