Topic Portal
Test instructions: A graph that changes to a specified figure, asking for a minimum number of steps
Analysis, the state transfer is simple, mainly in the storage of graphs and the problem of weighing, the original queue loaded with two-dimensional array of memory can also be sentenced to reuse the magic of the hash technology
#include <bits/stdc++.h>using namespace Std;const int MOD = 1e6 + 7;struct point{int ch[5][9];int x[4], Y[4];int Ste P;}; BOOL Vis[mod];int ha;int get_hash (int c[5][9]) {int tmp[60], k = 0;for (int i=1; i<=4; ++i) {for (int j=2; j<=8; ++j) { tmp[k++] = c[i][j]% 10;tmp[k++] = c[i][j]/10;}} int ret = 0;for (int i=0; i<k; ++i) {ret = (ret * 7 mod + tmp[i])% MoD;} ret = (ret & 0x7fffffff)% mod;return ret;} int init (void) {int Res[5][9];int x[4] = {One, one, +, 41};for (int i=0; i<4; ++i) {for (int j=1; j<=7; ++j) {res[i+1][j ] = x[i]++;} RES[I+1][8] = 0;} Return Get_hash (res);} void Change (point &v, int x0, int. y0, int k) {int a = V.ch[x0][y0-1] + 1;for (int i=1; i<=4; ++i) {for (int j=2; j< ; = 8; ++J) {if (v.ch[i][j] = = a) {V.x[k] = i;v.y[k] = J;swap (V.ch[x0][y0], v.ch[i][j]); return;}}} int BFS (point &p) {memset (Vis, false, sizeof (VIS)), int sh = get_hash (p.ch); Vis[sh] = true;queue<point> Que;que . push (P); while (!que.empty ()) {Point u = Que.front (); Que.pop(); int uh = Get_hash (u.ch); if (uh = = ha) {return u.step;} for (int i=0; i<4; ++i) {int x = U.x[i], y = u.y[i];if (y = = 1 | | u.ch[x][y]% = = 7) continue; Point v = u;change (V, x, y, i), int vh = Get_hash (v.ch), if (VIS[VH]) CONTINUE;VIS[VH] = True;v.step++;que.push (v);}} return-1;} int main (void) {ha = init (); int t;scanf ("%d", &t), while (t--) {Point p;p.step = 0;for (int i=1; i<=4; ++i) {p.ch[i][ 1] = 0;} for (int i=1; i<=4; ++i) {for (int j=2; j<=8; ++j) {scanf ("%d", &p.ch[i][j]);}} for (int i=1; i<=4; ++i) {(int j=2; j<=8; ++j) {if (p.ch[i][j] = =) {swap (p.ch[1][1], p.ch[i][j]);p. x[0] = i;p.y [0] = j;} else if (p.ch[i][j] = =) {swap (p.ch[2][1], p.ch[i][j]);p. x[1] = i;p.y[1] = j;} else if (p.ch[i][j] = =) {swap (p.ch[3][1], p.ch[i][j]);p. x[2] = i;p.y[2] = j;} else if (p.ch[i][j] = =) {swap (p.ch[4][1], p.ch[i][j]);p. x[3] = i;p.y[3] = j;}}} int ans = BFS (p);p rintf ("%d\n", ans);} return 0;}
Bfs+hash (storage, weight) hdoj 1067 Gap