https://www.acwing.com/problem/content/847/
#include <bits / STDC ++ H.> the using namespace STD; int BFS ( String Start) { String End = " 12345678x " ; Queue < String > Q; unordered_map < String , int > D; // distance array q.push (start ); // put into the start to D [start] = 0 ; // start point to the starting point distance of 0 int DX [ . 4 ] = { 0 , 0 , . 1 , - . 1}, Dy [ . 4 ] = { . 1 , - . 1 , 0 , 0 }; the while (q.size ()) { Auto T = q.front (); q.pop (); int Distance = D [T]; IF (t == end) return Distance; // determines whether t is terminated if the end // state transition int K = t.find ( ' x ' ); // first find the position x of the subscript x return int K = X / . 3 , Y =% K . 3 ; // the one dimension array to convert a two-dimensional 3x3 matrix array subscript for ( int I = 0 ; I < . 4 ; I ++ ) { int A = X + DX [I], B = Y + Dy [I]; // coordinate after the change IF (A> = 0 && A < . 3 && B> = 0 && B < . 3 ) // If not out of bounds { the swap (T [K], T [A * . 3 + B]); // after update exchange must be completed recovery state update IF (d.count (T!) ) // If t is after the current has not been found to have updated it had found a new state { D [t] = Distance + . 1 ; //Plus the distance. 1 q.push (T); // pressed into queue } the swap (T [K], T [A * . 3 + B]); // recovery state } } } return - . 1 ; } int main () { string Start; // initially given string for ( int I = 0 ; I < . 9 ; I ++ ) { char C; CIN >> C; Start + = C; } COUT<<bfs(start)<<endl; }