I really served, bfs+ Kang expand, of course, this is a relatively low-level approach, in the future I will update other practices
The eight-digit question seems to be quite famous.
The title is to give you a 3*3 matrix filled with 1-8 of the numbers empty a lattice, our goal is to let this matrix arranged into
1 2 3
4 5 6
7 8 x x is empty.
Method one: Treat X as 9, from 1 2 3 4 5 6 7 8 to 9, search all states, record the path to all States, enter a starting state, direct output path
This is the stupidest way, I see there are many a * on the net, two-way BFS, deeply own weak
(I started with a map timeout)
#include <iostream>#include<queue>#include<cstring>#include<vector>#include<cstdio>#include<cmath>#include<map>#include<string>using namespacestd;#definell Long Long#defineSe Second#defineFi first#defineOO 0x3fffffffConst intMAXN =400000;BOOLHASHS[MAXN];stringPATH[MAXN];intfac[]={1,1,2,6, -, -,720,5040,40320,362880};intdx[4] = {1,-1,0,0};intdy[4] = {0,0,1,-1};Charop[5] ="UDLR";structnode{ints[9]; intPOS; intVal; stringpath;};intTocon (inta[]) { intx =0; for(inti =0; I <=8; ++i) {intK =0; for(intj = i+1; J <=8; ++j)if(A[j] > A[i]) k + +; X+ = k*fac[9-i-1]; } returnx;}voidBFs () {intnum[9]; memset (HASHS,0,sizeof(HASHS)); Node st,ed; for(inti =0; I <9; ++i) st.s[i]= i+1; St.val=Tocon (ST.S); St.path=""; Path[st.val]=""; Hashs[st.val]=true; St.pos=8; Queue<node>Q; Q.push (ST); while(!Q.empty ()) {St=Q.front (); Q.pop (); for(inti =0; I <4; ++i) {intxx = st.pos/3+Dx[i]; intyy = st.pos%3+Dy[i]; if(XX >=0&& xx <=2&& yy >=0&& yy <=2) {Ed.pos= xx*3+yy; for(inti =0; I <9; ++i) ed.s[i]=St.s[i]; //for (int i = 0; i < 9; ++i)//cout << Ed.s[i]; //cout << Endl;swap (Ed.s[ed.pos],ed.s[st.pos]); Ed.val=Tocon (Ed.S); if(!Hashs[ed.val]) {Hashs[ed.val]=true; Ed.path= Op[i] +St.path; Path[ed.val]=Ed.path; Q.push (ed); } } } }}intMain () {Charstr[ Max]; BFS (); while(gets (str)) {ints[9]; intL =0; for(inti =0; I < strlen (str); ++i) {if(Str[i] <='9'&& Str[i] >='0') S[l+ +] = Str[i]-'0'; Else if(Str[i] = ='x') S[l++] =9; } intK =Tocon (s); if(Hashs[k]) cout << Path[k] <<Endl; Elsecout<<"unsolvable"<<Endl; }}
Eight-digit number