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
| Node::Node(int p, int cal, int d[9]) { this->p = p; this->cal = cal; for (int i = 0; i < 9; i++) { data[i] = d[i]; } }
Queue::Queue() { front = close = open = new Node(); }
void Queue::EnQueue(Node *n) { n->next = NULL; n->father = close; open->next = n; open = n; return; }
int Queue::DeQueue() { if (close->next) { close = close->next; } else { return -1; }
int p = close->p; if (CanGo(p, 1)) { Node* n = new Node(p - 1, 1, close->data); n->data[p - 1] = n->data[p - 2]; n->data[p - 2] = 0; if (equal(n->data, target)) { EnQueue(n); return 1; } if (!IsExist(n->data)) EnQueue(n); } if (CanGo(p, 2)) { Node* n = new Node(p - 3, 2, close->data); n->data[p - 1] = n->data[p - 4]; n->data[p - 4] = 0; if (equal(n->data, target)) { EnQueue(n); return 1; } if (!IsExist(n->data)) EnQueue(n); } if (CanGo(p, 3)) { Node* n = new Node(p + 3, 3, close->data); n->data[p - 1] = n->data[p + 2]; n->data[p + 2] = 0; if (equal(n->data, target)) { EnQueue(n); return 1; } if (!IsExist(n->data)) EnQueue(n); } if (CanGo(p, 4)) { Node* n = new Node(p + 1, 4, close->data); n->data[p - 1] = n->data[p]; n->data[p] = 0; if (equal(n->data, target)) { EnQueue(n); return 1; } if (!IsExist(n->data)) EnQueue(n); } return 0; }
bool Queue::IsEnd() { if (close == open) return true; else return false; }
bool Queue::IsExist(int d[9]) { Node* tmp = front; do { tmp = tmp->next; if (equal(tmp->data, d)) return true; } while (tmp->next); return false; }
void Queue::PrintResult() { Node* tmp = open; for (int i = 0; i < 9; i++) { cout << tmp->data[i] << "\t"; if (i % 3 == 2) cout << endl; } while (tmp->father->p > 0) { tmp = tmp->father; cout << endl << "\t/\\" << endl << "\t||" << endl << endl; for (int i = 0; i < 9; i++) { cout << tmp->data[i] << "\t"; if (i % 3 == 2) cout << endl; } } }
bool CanGo(int p, int cal) { if (cal == 1 && p != 1 && p != 4 && p != 7) return true; if (cal == 2 && p != 1 && p != 2 && p != 3) return true; if (cal == 3 && p != 7 && p != 8 && p != 9) return true; if (cal == 4 && p != 3 && p != 6 && p != 9) return true; return false; }
bool equal(int d1[9], int d2[9]) { int i; for (i = 0; i < 9; i++) { if (d1[i] != d2[i]) { break; } } if (i >= 9) return true; return false; }
|