/* Problem Description: Initial Status: 1 2 34 5 67 8 0 Enter the final state, the number of steps for the initial state to the final state, or the number of steps if the number of steps is less than or equal to 5, otherwise the output -1*/#include "iostream" #include "string" #include " Queue "#include" vector "#include" algorithm "using namespace Std;const int Direction[4][2] = {{0,-1}, {0, 1}, {-1, 0 }, {1, 0}}; 0 Moving Direction const string init = "123456780"; Initial state const int num = 3; struct node{string state;int depth;//number of steps to this node int zero,//0 position node (int d = 0, string s = "", int z = 8):d epth (d), state (s ), zero (z) {}};int main (int argc, char *argv[]) {int t;cin >> t;//number of test cases while (t--) {string target = ""; Target State for (int i = 0; i < num * num; i++) {string tmp;cin >> Tmp;target + tmp;} Queue<node> openlist;vector<string> closelist; Store the visited state Openlist.push (Node (0, Init, 8)); int depth = 0;bool flag = False;while (!openlist.empty () && depth <= 5) {Node head = Openlist.front ();d epth = head.depth;if (head.state = = target) {flag = True;break;} int oldr = Head.zero/num; 0 row int oldc = head.zero% num; 0 column for (int i = 0; I < 4; i++) {int NEWR = Oldr + direction[i][0];int NEWC = oldc + direction[i][1];if (newr >= 0 && newr < num &&A mp NEWC >= 0 && newc < num) {int newpos = NEWR * 3 + newc;//0 new position string newstate = Head.state;newstate[head.zer O] = head.state[newpos];newstate[newpos] = ' 0 '; if (Find (Closelist.begin (), Closelist.end (), newstate) = = Closelist.end ( )) Openlist.push (Node (head.depth + 1, newstate, Newpos));}} Openlist.pop (); Closelist.push_back (head.state);} if (flag) {cout << depth << Endl;} Else{cout << 1 << endl;//1 2 3 4 5 0 7 8 6//2 3 4 1 5 0 7 6 8}}return 0;}
Simple eight-digit question