struct Node //结构体的节点 { int id; int visited; int step; string present; //记录当前魔板状态 vector<char> record; //记录魔板移动路径 }node[500000];
queue<int> q;
void initial( Node &node ); int factorial( int x ); int cantorCode( string line ); //康托编码的函数 void operateA( string line, int lastId ); //三种魔板移动操作 void operateB( string line, int lastId ); void operateC( string line, int lastId );
int main() { int step; while( cin>>step && step != -1 ) //读取步数的限制 { for( int i = 0; i < 50000; i++ ) initial( node[ i ] ); while (!q.empty()) q.pop(); int input[ 8 ]; //存目标状态的数组 string goal, present, hold; int id; for( int i = 0; i < 8; i++ ) { cin>>input[ i ]; goal += input[ i ] + '0';//把数组转变成string类型的goal } for( int i = 0; i < 4; i++ )//把数组转变成string的初始状态present { //第一排 input[ i ] = i + 1; present += input[ i ] + '0'; } int value = 8; for( int i = 4; i < 8; i++ )//把数组转变成string的初始状态present { //第二排 present += value + '0'; value--; } id = cantorCode( present );//把初始状态进行康托编码,获取对应id node[ id ].present = present;//把初始状态创建成节点 node[ id ].visited = 1; q.push( id ); //初始节点入队列,便于BFS遍历 while( !q.empty() ) //BFS遍历 { id = q.front(); if( node[ id ].present == goal ) { if( node[ id ].step <= step )//如果超过最大步数限制则显示失败 { cout<<node[ id ].step<<" "; for( int i = 0; i < node[ id ].step; i++ ) cout<<node[ id ].record[ i ]; cout<<endl; } else cout<<"-1"<<endl; //失败提示 } hold = node[ id ].present; //BFS遍历 operateA( hold, id ); hold = node[ id ].present; operateB( hold, id ); hold = node[ id ].present; operateC( hold, id ); q.pop(); } } system("pause"); return 0; }