BFS + 剪枝 之 hdu 5012 Dice
/*
BFS 遍历所有状态,当寻找到要转到的状态,输出BFS的层数,即答案,否则输出 -1;
注意:
剪枝: 当BFS到某一种状态时,若此状态已在前面所寻找的状态中出现过,则不用再继续从此状态BFS了,因为此状态所能寻找的状态已经在之前都处理过了。
*/
1 #include <iostream> 2 #include <cstdlib> 3 #include <cstdio> 4 #include <queue> 5 #include <vector> 6 #include <map> 7 using namespace std; 8 struct myNode { 9 int Top, Bottom, Left, Right, Front, Back; 10 }; 11 typedef pair<myNode, int> P; 12 13 myNode node[2]; 14 vector<myNode> vec; 15 16 void myDeal(int myCase, myNode myNd, myNode &t_Nd) { 17 // top face, bottom face, left face, right face, front face and back face 18 switch (myCase) { 19 case 1: { 20 t_Nd.Top = myNd.Right; 21 t_Nd.Bottom = myNd.Left; 22 t_Nd.Left = myNd.Top; 23 t_Nd.Right = myNd.Bottom; 24 t_Nd.Front = myNd.Front; 25 t_Nd.Back = myNd.Back; 26 return; 27 } 28 case 2: { 29 t_Nd.Top = myNd.Left; 30 t_Nd.Bottom = myNd.Right; 31 t_Nd.Left = myNd.Bottom; 32 t_Nd.Right = myNd.Top; 33 t_Nd.Front = myNd.Front; 34 t_Nd.Back = myNd.Back; 35 return; 36 } 37 case 3: { 38 t_Nd.Top = myNd.Back; 39 t_Nd.Bottom = myNd.Front; 40 t_Nd.Front = myNd.Top; 41 t_Nd.Back = myNd.Bottom; 42 t_Nd.Left = myNd.Left; 43 t_Nd.Right = myNd.Right; 44 return; 45 } 46 case 4: { 47 t_Nd.Top = myNd.Front; 48 t_Nd.Bottom = myNd.Back; 49 t_Nd.Front = myNd.Bottom; 50 t_Nd.Back = myNd.Top; 51 t_Nd.Left = myNd.Left; 52 t_Nd.Right = myNd.Right; 53 return; 54 } 55 default: 56 system("pause"); 57 return; 58 } 59 } 60 61 bool myJudge(const myNode n1, const myNode n2) { 62 if ((n1.Top == n2.Top) && (n1.Bottom == n2.Bottom) && (n1.Front == n2.Front) && 63 (n1.Back == n2.Back) && (n1.Left == n2.Left) && (n1.Right == n2.Right)) { 64 return true; 65 } 66 return false; 67 } 68 69 bool Judge(myNode nd) { 70 for (int i = 0; i < vec.size(); ++i) { 71 if (myJudge(vec[i], nd)) { 72 return true; 73 } 74 } 75 return false; 76 } 77 78 void Solve() { 79 queue<P> que; 80 que.push(P(node[0], 0)); 81 while (!que.empty()) { 82 P p1 = que.front(); 83 if (Judge(p1.first)){ 84 //cout << "Yes" << endl; 85 que.pop(); 86 continue; 87 } 88 vec.push_back(p1.first); 89 que.pop(); 90 if (myJudge(p1.first, node[1])) { 91 printf("%d\n", p1.second); 92 return; 93 } 94 myNode t_Nd; 95 for (int i = 1; i <= 4; ++i) { 96 myDeal(i, p1.first, t_Nd); 97 //cout << t_Nd.Top << " " << t_Nd.Bottom << " " << t_Nd.Left << " " << t_Nd.Right << " " << t_Nd.Front << " " << t_Nd.Back << endl; 98 que.push(P(t_Nd, p1.second + 1)); 99 } 100 } 101 printf("-1\n"); 102 } 103 104 int main() { 105 //freopen("input.txt", "r", stdin); 106 int n; 107 while (~scanf("%d %d %d %d %d %d", &node[0].Top, &node[0].Bottom, &node[0].Left, &node[0].Right, &node[0].Front, &node[0].Back)) { 108 scanf("%d %d %d %d %d %d", &node[1].Top, &node[1].Bottom, &node[1].Left, &node[1].Right, &node[1].Front, &node[1].Back); 109 Solve(); 110 if (!vec.empty()) vec.clear(); 111 } 112 return 0; 113 }