题目描述
*WWBB
WWBB*
WWW*BBB
BBB*WWW
2
10
1 #include<bits/stdc++.h> 2 #define inf 0x3f3f3f3f 3 typedef long long ll; 4 using namespace std; 5 string a,b; 6 map<string,int>sigmap; 7 class node{ 8 public: 9 string s; 10 int step; 11 int id; 12 node(string S,int step,int id){ 13 this->s=S; 14 this->step = step; 15 this->id=id; 16 } 17 }; 18 void bfs() 19 { 20 queue<node>myque; 21 if(a==b) 22 cout<<0<<endl; 23 else{ 24 node Nod=node(a,0,a.find(‘*‘)); 25 myque.push(Nod); 26 sigmap[a]=1; 27 while(!myque.empty()){ 28 Nod=myque.front(); 29 myque.pop(); 30 for(int i=Nod.id-3; i<=Nod.id+3; i++){ 31 if(i>=0&&i<Nod.s.length()&&i!=Nod.id){ 32 string S=Nod.s; 33 swap(S[i],S[Nod.id]); 34 if(sigmap[S] == 1) 35 continue; 36 if(S==b){ 37 cout<<Nod.step+1<<endl; 38 return; 39 } 40 sigmap[S]=1; 41 node now=node(S,Nod.step+1,i); 42 myque.push(now); 43 } 44 } 45 } 46 } 47 } 48 int main() 49 { 50 while(cin>>a){ 51 cin>>b; 52 bfs(); 53 } 54 return 0; 55 }
BFS(广度优先搜索遍历保存全局状态,华容道翻版做法)--08--DFS--蓝桥杯青蛙跳杯子
原文:https://www.cnblogs.com/qinqin-me/p/12259948.html