HDU 3713 Double Maze
代码写了很久才调通——!双迷宫搜索 不过状态数不大 只有6^4次 主要是地图的处理 以及居然要相邻两个地图都要求解一次 还有用到掩码也就是位运算来确定当前位置的四个方向是否有墙以及是否是洞…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | #include <stdio.h> #include <string.h> #include <stack> using std::stack; int hash[6][6][6][6], dirx[] = {0,1,0,-1}, diry[] = {-1,0,1,0}, map1[6][6], map2[6][6], choice[4] = {1,0,2,3}; char dirc[] = "LDRU"; struct Point { int x, y; void operator = (const Point & p) { x = p.x; y = p.y; } bool operator == (const Point & p) { return x == p.x && y == p.y; } }pnt[2]; struct State { Point a, b; int father, drt; bool operator == (const State &cmp) { return a == cmp.a && b == cmp.b; } bool valid() { return (map1[a.x][a.y] & (1<< 4)) != 0&& (map2[b.x][b.y] & (1<< 4)) != 0 && a.x >= 0 && a.y >= 0 && b.x >= 0 && b.y >=0 && a.x < 6 && a.y < 6 && b.x < 6 && b.y < 6; } State trans(int dir, int idx) { State ret; ret.drt = dir; ret.father = idx; if((map1[a.x][a.y] & (1 << dir)) == 0) { ret.a.x = a.x + dirx[dir]; ret.a.y = a.y + diry[dir]; } else { ret.a.x = a.x; ret.a.y = a.y; } if((map2[b.x][b.y] & (1 << dir)) == 0) { ret.b.x = b.x + dirx[dir]; ret.b.y = b.y + diry[dir]; } else { ret.b.x = b.x; ret.b.y = b.y; } return ret; } void set(Point p1, Point p2) { a = p1, b = p2; } State() { father = -1; } }s1,s2,tmp,queue[1300],ns; inline void makehash(State s) { hash[s.a.x][s.a.y][s.b.x][s.b.y] = 1; } inline bool checkhash(State s) { return hash[s.a.x][s.a.y][s.b.x][s.b.y] == 0; } void read(int map[6][6]) { for(int i = 0; i < 6; ++ i) for(int j = 0; j < 6; ++ j) { scanf("%d",map[i]+j); if((map[i][j] &(1 << 5)) != 0) pnt[0].x = i, pnt[0].y = j; if((map[i][j] & (1 << 6)) != 0) pnt[1].x = i, pnt[1].y = j; } } int main() { int n, head, tail; scanf("%d", &n); read(map1); s1.a = pnt[0]; s2.a = pnt[1]; while(--n) { memset(hash, 0, sizeof(hash)); stack<char> stk; read(map2); s1.b = pnt[0]; s2.b = pnt[1]; head = tail = 0; queue[tail++] = s1; makehash(s1); while(head < tail) { tmp = queue[head]; if(tmp == s2) { for(int f = head; f > 0; f = queue[f].father) stk.push(dirc[queue[f].drt]); while(!stk.empty()) { putchar(stk.top()); stk.pop(); } puts(""); break; } for(int i = 0; i < 4; ++ i) { ns = tmp.trans(choice[i], head); if(ns.valid() && checkhash(ns)) { queue[tail++] = ns; makehash(ns); } } ++ head; } if(head >= tail) puts("-1"); memcpy(map1, map2, sizeof(map1)); s1.a = s1.b; s2.a = s2.b; } return 0; } |