这是一道poj1184的题目,由于求解的是最优解,所以首先想到的就是使用广度优先搜索。对于这道题目我同时使用set容器,来作为状态判重。 代码如下: /* * POJ 1184 聪明的打字员 * 版本1 : 普通的广度搜索 ,使用set进行状态判重 */ #include<iostream> #include<queue> #include<set> #include<ctime> //#include<fstream> #define CODE_LENGTH 6 using namespace std; typedef struct str{ int step; string code; int pos; //光标的位置 str(){} //光标的初始位置为0 str(int s , string c):step(s),code(c),pos(0){} //重载operator< friend bool operator<(const str& a, const str& b) { if(a.code < b.code ) return true; if(a.code > b.code ) return false; if( a.pos < b.pos ) return true; if( a.pos > b.pos) return false ; return false ; } }Str; typedef pair<set<Str>::iterator,bool> Pair; queue<Str> Queue; //bfs的队列的数据结构 set<Str> HashSet; //状态判重的set //ofstream out("result.txt"); static int pushNUM=0; //index :标记使用的操作 //state:表示当前节点 Str changeCode(const Str& state,const int& index){ Str tmp = state ; char c; //1 : swap0 2: swap1 3:up 4:down 5:left 6:right switch( index ){ case 1: if( 0 == tmp.pos ) {} else { c= tmp.code[0]; tmp.code[0]= tmp.code[tmp.pos]; tmp.code[tmp.pos] = c; } break; case 2: if( 5 == tmp.pos ) {} else{ c = tmp.code[5]; tmp.code[5]= tmp.code[tmp.pos]; tmp.code[ tmp.pos] = c ; } break; //注意这里是字符不是数字 case 3: if( '9' == tmp.code[ tmp.pos ] ){} else{ tmp.code[tmp.pos] += 1 ; } break; case 4: if( '0' == tmp.code[ tmp.pos ] ){} else{ tmp.code[tmp.pos] -= 1 ; } break; case 5: if( 0 == tmp.pos ) {} else{ tmp.pos -=1 ; } break; case 6: if( 5 == tmp.pos ){} else{ tmp.pos += 1; } break; default: cout<<"ERROR!"<<endl; break; } tmp.step +=1 ; return tmp; } void bfsSearch(const Str& org,Str& dest){ //step1: push the original node into the queue Queue.push(org); HashSet.insert(org); Str curr,tmp; Pair check; while(! Queue.empty()){ curr = Queue.front(); Queue.pop(); //step2 : check wether find the target node if( dest.code == curr.code){ dest.step = curr.step ; return ; } for(int i=1; i<=6 ;i++){ tmp = changeCode(curr,i); check = HashSet.insert(tmp); //检查是否为