bfs通解,,,用了set存放状态以保证第一次找到目标答案
1 // 2 // Created by snnnow on 2020/7/29. 3 // 4 5 #include<bits/stdc++.h> 6 using namespace std; 7 struct node { 8 string str; 9 int step; 10 int pos; 11 node (string str,int step,int pos):str(str),pos(pos),step(step){} 12 }; 13 set <string> vis; 14 queue <node> q; 15 void Insert_Inq(node temp,int i) 16 { 17 string str = temp.str; 18 swap(str[temp.pos],str[(temp.pos+i+9)%9]); 19 if(vis.count(str)==0) 20 { 21 vis.insert(str); 22 node n (str,temp.step+1,(temp.pos+i+9)%9); 23 q.push(n); 24 } 25 } 26 int main () 27 { 28 29 node first ("012345678",0,0); 30 q.push(first); 31 while (!q.empty()) 32 { 33 node temp = q.front(); 34 if(temp.str=="087654321") 35 { 36 cout<<temp.step; 37 break; 38 } 39 else { 40 Insert_Inq(temp,1); 41 Insert_Inq(temp,-1); 42 Insert_Inq(temp,2); 43 Insert_Inq(temp,-2); 44 q.pop(); 45 } 46 } 47 return 0; 48 }