Purple Book gives is the state space search, in fact, the subject can also be used ida* algorithm, because it conforms to the characteristics of ida*: To find the minimum number of iterations.
According to the law of rotation, we can use a few arrays to store the rotation in all directions to change what amount, to maintain the rotation of this operation. Another is the valuation function: currently in the middle of the eight most times the number is set to T, then the remaining number of iterations is 8-t, if it is added to the number of iterations D > maxd, it should be pruned.
In addition, a good way to estimate the time complexity of backtracking: generally in each layer into the next layer of the possible number set to T, the maximum number of iterations set to D, then the time complexity of POW (t,d);
See the code for details:
#include <bits/stdc++.h>using namespace Std;int a[30],maxd,path[100000];int Roller[8][7] = {{0,2,6,11,15,20,22} , {1,3,8,12,17,21,23},{10,9,8,7,6,5,4},{19,18,17,16,15,14,13},{23,21,17,12,8,3,1},{22,20,15,11,6,2,0},{ 13,14,15,16,17,18,19},{4,5,6,7,8,9,10}};int Goalpos[8] = {6,7,8,11,12,15,16,17};int Bac[8] = {5, 4, 7, 6, 1, 0, 3, 2};void Rot (int *aa,int dir) {for (int i=1;i<7;i++) {int t = aa[roller[dir][i]]; Aa[roller[dir][i]] = aa[roller[dir][i-1]]; Aa[roller[dir][i-1]] = t; }}bool DFS (int d) {if (d = = Maxd) {for (int i=1;i<8;i++) {if (a[goalpos[i]]! = A[goalpos[i-1]]) r Eturn false; } if (!d) {printf ("No moves needed\n%d\n", a[6]); return true;} for (int i=0;i<d;i++) printf ("%c", path[i]+ ' A '); printf ("\n%d\n", a[6]); return true; } else {int res = 0; int a1 = 0, B = 0, c = 0; for (int i=0;i<8;i++) {if (a[goalpos[i] = = 1) ++a1; else if (a[gOalpos[i]] = = 2) ++b; else if (a[goalpos[i]] = = 3) ++c; } res = 8-max (A1,max (b,c)); if (d + res > Maxd) return false; for (int i=0;i<8;i++) {Path[d] = i; Rot (a,i); if (Dfs (d+1)) return true; Rot (A,bac[i]); }} return false;} int main () {while (~SCANF ("%d", &a[0]) &&a[0]) {for (int i=1;i<24;i++) scanf ("%d", &a[i]); for (maxd = 0;; ++maxd) {if (DFS (0)) break; }} return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
1343-the Rotation Game (ida* algorithm)