Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / pipes / numberlink_solver.cpp

numberlink_solver.cpp339 lines · 10.8 KiBRaw
1// numberlink_solver - Number Link Solver based on ZDD.
2//
3// Copyright (C) 2011 Kentaro Imajo. All rights reserved.
4// Author: Kentaro Imajo (Twitter: imos)
5//
6// This program uses special ordered cell keys. From the upper-left-most cell
7// to bottom-right-most cell, it traces every cell with diagonal lines from
8// upper-right to bottom-left. For 4x4 table, we use the order that is denoted
9// in the following table.
10// 00 01 03 06
11// 02 04 07 10
12// 05 08 11 13
13// 09 12 14 15
14//
15// This program inputs some datasets from the standard input. Each dataset
16// should have `width' and `height' in this order with a space delimiter in
17// the first line, and each of the following height lines should have width
18// integers. Zeroes represent blank cells, and one or more represent
19// themselves. For the NumberLink problem (the left figure), you should use the
20// input (the right figure).
21//
22// +---+---+---+---+ Standard Input:
23// | 1 2 | 4 3
24// + + + + + 1 0 0 2
25// | 3 1 | 0 3 1 0
26// + + + + + 3 2 0 0
27// | 3 2 |
28// +---+---+---+---+
29
30#include <cstdio>
31#include <cstring>
32#include <map>
33#include <memory>
34#include <stack>
35#include <vector>
36using namespace std;
37
38bool FLAGS_color = false;
39
40class NumberLink {
41 public:
42 // The type of the number written in a cell
43 typedef char CellNumber;
44 // The type of the ID number of a cell
45 typedef short CellKey;
46 // The type of a coordinate represented by (y * width + x)
47 typedef short CellPosition;
48 // The type of a distance such as width, height, x and y
49 typedef int Distance;
50 // The size of the NumberLink task
51 Distance width_;
52 Distance height_;
53
54 NumberLink(const Distance width, const Distance height):
55 width_(width), height_(height), size_((CellKey)width * height),
56 cell_x_(size_), cell_y_(size_), table_(size_),
57 keys_(size_), mates_(size_), start_(size_ + 1),
58 connected_x_(size_), connected_y_(size_), memo_(size_) {}
59
60 void Initialize() {
61 // Initialize mates
62 for (CellKey cell_key = 0; cell_key < size_; cell_key++) {
63 mates_[cell_key] = cell_key;
64 }
65
66 // Generates references: (x, y) <=> CellKey
67 Distance x = 0, y = 0;
68 CellKey cell_key = 0;
69 while (true) {
70 CellPosition position = (CellPosition)y * width_ + x;
71 cell_x_[cell_key] = x;
72 cell_y_[cell_key] = y;
73 keys_[position] = cell_key;
74 cell_key++;
75 if (cell_key == size_) break;
76 do {
77 x--;
78 y++;
79 if (x < 0) {
80 x = y;
81 y = 0;
82 }
83 } while (x < 0 || width_ <= x || y < 0 || height_ <= y);
84 }
85
86 // Pre-compute CellKey to look back for every cell
87 for (CellKey i = 0; i < size_; i++) {
88 Distance x = cell_x_[i], y = cell_y_[i];
89 start_[i] = 0 < y ? GetCellKey(x, y - 1) :
90 (0 < x ? GetCellKey(x - 1, y) : 0);
91 }
92 // For a guard
93 start_[size_] = size_;
94 }
95
96 // Returns the reference of the number written in the cell (x,y).
97 CellNumber& Cell(const Distance x, const Distance y)
98 { return table_[GetCellKey(x, y)]; }
99 // Returns the key of the special order for the coordinate (x,y).
100 CellKey GetCellKey(const Distance x, const Distance y) const
101 { return keys_[(CellPosition)y * width_ + x]; }
102
103 double Solve(const CellKey cell_key = 0) {
104 if (cell_key == 0) {
105 solved_ = false;
106 // Holes (table_ == -1) are permanently "interior": no incident
107 // edges, no coverage requirement. Mark their mate as -1 so they
108 // are never required to connect. Done here (not in Initialize)
109 // because the table is populated after Initialize().
110 for (CellKey k = 0; k < size_; k++) {
111 if (table_[k] == -1) mates_[k] = -1;
112 }
113 }
114 // See the newly fixed cells
115 if (0 < cell_key) {
116 for (CellKey hidden = start_[cell_key - 1];
117 hidden < start_[cell_key]; hidden++) {
118 // Holes have no coverage requirement
119 if (table_[hidden] == -1) continue;
120 if (table_[hidden] == 0) {
121 // Return if the empty cell has an end
122 if (mates_[hidden] != -1 && mates_[hidden] != hidden) return 0.0;
123 } else {
124 // Return if the numbered cell has no line
125 if (mates_[hidden] == hidden) return 0.0;
126 }
127 }
128 }
129 // If all the cells are filled
130 if (cell_key == size_) {
131 if (!solved_) {
132 Print();
133 solved_ = true;
134 }
135 return 1.0;
136 }
137
138 // Connect successive cells if this sequence of mates has not been seen
139 const vector<CellKey> mate_tuple(mates_.begin() + start_[cell_key],
140 mates_.begin() + cell_key);
141 const Hash mate_hash = GetHash(mate_tuple);
142 if (!memo_[cell_key].count(mate_hash)) {
143 memo_[cell_key][mate_hash] = Connect(cell_key);
144 }
145 return memo_[cell_key][mate_hash];
146 }
147
148 double Connect(const CellKey cell_key) {
149 double solution_count = 0.0;
150 Distance x = cell_x_[cell_key], y = cell_y_[cell_key];
151 // Holes have no incident edges: take only the "connect nothing" branch
152 if (table_[cell_key] == -1) {
153 return Solve(cell_key + 1);
154 }
155 CellKey left_cell_key = -1, up_cell_key = -1;
156 if (0 < x) left_cell_key = GetCellKey(x - 1, y);
157 if (0 < y) up_cell_key = GetCellKey(x, y - 1);
158 // Never link to a hole neighbour: treat it as absent
159 if (0 <= left_cell_key && table_[left_cell_key] == -1) left_cell_key = -1;
160 if (0 <= up_cell_key && table_[up_cell_key] == -1) up_cell_key = -1;
161 size_t revert_point = mate_stack_.size();
162 // Connect the cell with nothing
163 solution_count += Solve(cell_key + 1);
164 // Connect the cell with the upper cell
165 if (0 <= up_cell_key) {
166 if (UniteMates(cell_key, up_cell_key)) {
167 connected_y_[cell_key] = true;
168 solution_count += Solve(cell_key + 1);
169 connected_y_[cell_key] = false;
170 }
171 RevertMates(revert_point);
172 }
173 // Connect the cell with the left cell
174 if (0 <= left_cell_key) {
175 if (UniteMates(cell_key, left_cell_key)) {
176 connected_x_[cell_key] = true;
177 solution_count += Solve(cell_key + 1);
178 // Connect the cell with the upper and the left cells
179 if (0 <= up_cell_key) {
180 if (UniteMates(cell_key, up_cell_key)) {
181 connected_y_[cell_key] = true;
182 solution_count += Solve(cell_key + 1);
183 connected_y_[cell_key] = false;
184 }
185 }
186 connected_x_[cell_key] = false;
187 }
188 RevertMates(revert_point);
189 }
190 return solution_count;
191 }
192
193 void Print() {
194 for (Distance y = 0; y <= height_; y++) {
195 for (Distance x = 0; x < width_; x++) {
196 printf(FLAGS_color ? "\x1b[32m+\x1b[0m" : "+");
197 printf((y % height_ == 0) ?
198 (FLAGS_color ? "\x1b[32m---\x1b[0m" : "---") :
199 (connected_y_[GetCellKey(x, y)] ? " # " : " "));
200 }
201 puts(FLAGS_color ? "\x1b[32m+\x1b[0m" : "+");
202 if (height_ <= y) break;
203 for (Distance x = 0; x < width_; x++) {
204 printf(x ? (connected_x_[GetCellKey(x, y)] ? "#" : " ") :
205 (FLAGS_color ? "\x1b[32m|\x1b[0m" : "|"));
206 if (table_[GetCellKey(x, y)]) {
207 printf("%03d", table_[GetCellKey(x, y)]);
208 } else {
209 printf(connected_x_[GetCellKey(x, y)] ? "#" : " ");
210 printf(mates_[GetCellKey(x, y)] == GetCellKey(x, y) ? " " : "#");
211 printf((x + 1 < width_ && connected_x_[GetCellKey(x + 1, y)])
212 ? "#" : " ");
213 }
214 }
215 puts(FLAGS_color ? "\x1b[32m|\x1b[0m" : "|");
216 }
217 }
218
219 private:
220 // Hash key to identify a sequence of CellKeys
221 typedef pair<long long, long long> Hash;
222 // The number of cells on the board
223 CellKey size_;
224 // History of modification
225 stack< pair<CellKey, CellKey> > mate_stack_;
226 // Map from a CellKey to a coordinate
227 vector<Distance> cell_x_, cell_y_;
228 // Store the numbers in the cells
229 vector<CellNumber> table_;
230 vector<CellKey> keys_, mates_, start_;
231 // Description of links on the board
232 vector<bool> connected_x_, connected_y_;
233 // Hash table to identify a sequence of CellKeys
234 vector< map<Hash, double> > memo_;
235 // Flag to know whether the problem has been solved
236 bool solved_;
237
238 // Get a hash key based on the XorShift algorithm
239 Hash GetHash(const vector<CellKey> &cell_keys) {
240 unsigned int x = 123456789, y = 362436069, z = 521288629, w = 88675123;
241 for (int i = 0; i < (int)cell_keys.size(); i++) {
242 unsigned int t = (x ^ (x << 11)); x = y; y = z; z = w;
243 w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)) + (unsigned int)cell_keys[i];
244 }
245 Hash h;
246 h.first = ((unsigned long long)x << 32) | y;
247 h.second = ((unsigned long long)z << 32) | w;
248 return h;
249 }
250
251 // Change the table of mates in adding the history
252 int ChangeMates(const CellKey cell_key, const CellKey cell_value) {
253 int last_stack_size = mate_stack_.size();
254 CellKey last_value = mates_[cell_key];
255 if (last_value != cell_value) {
256 mate_stack_.push(make_pair(cell_key, last_value));
257 mates_[cell_key] = cell_value;
258 }
259 return last_stack_size;
260 }
261
262 // Revert the table of mates using the history
263 void RevertMates(const size_t stack_size) {
264 for (; stack_size < mate_stack_.size(); mate_stack_.pop())
265 mates_[mate_stack_.top().first] = mate_stack_.top().second;
266 }
267
268 // Connects cell_key1 and cell_key2 by a line. Returns false if it cannot
269 // connect the cells because of constraints. The table of mates must be
270 // reverted even if the cells cannot be connect correctly.
271 bool UniteMates(const CellKey cell_key1, const CellKey cell_key2) {
272 CellKey end1 = mates_[cell_key1], end2 = mates_[cell_key2];
273 // Cannot connect any branch
274 if (end1 == -1 || end2 == -1) return false;
275 // Avoid making a cycle
276 if (cell_key1 == end2 && cell_key2 == end1) return false;
277 // Change states of mates to connect cell_key1 and cell_key2
278 ChangeMates(cell_key1, -1);
279 ChangeMates(cell_key2, -1);
280 ChangeMates(end1, end2);
281 ChangeMates(end2, end1);
282 // Check three constraints:
283 // 1. cell_key1 must not be a branch if cell_key1 is numbered,
284 // 2. cell_key2 must not be a branch if cell_key2 is numbered,
285 // 3. Different numbers cannot be connected.
286 if (mates_[cell_key1] == -1 && 0 < table_[cell_key1]) return false;
287 if (mates_[cell_key2] == -1 && 0 < table_[cell_key2]) return false;
288 if (0 < table_[end1] && 0 < table_[end2] &&
289 table_[end1] != table_[end2]) return false;
290 return true;
291 }
292};
293
294void ParseArguments(int *argc, char **argv) {
295 int arg_pos = 1;
296 for (int i = 1; i < *argc; i++) {
297 char *flag = argv[i];
298 if (flag[0] == '-' && flag[1] == '-') {
299 char *key = flag + 2, *value = strstr(key, "=");
300 if (value) {
301 *value = 0;
302 value++;
303 }
304 if (strcmp(key, "color") == 0) {
305 FLAGS_color = true;
306 }
307 } else {
308 argv[arg_pos] = argv[i];
309 arg_pos++;
310 }
311 }
312 *argc = arg_pos;
313}
314
315int main(int argc, char **argv) {
316 ParseArguments(&argc, argv);
317 int width, height;
318 // Until the input ends or 0x0 is given
319 while (2 == scanf("%d%d", &width, &height) && width && height) {
320 NumberLink nl((int)width, (int)height);
321 nl.Initialize();
322 for (int y = 0; y < nl.height_; y++) {
323 for (int x = 0; x < nl.width_; x++) {
324 int value;
325 scanf("%d", &value);
326 nl.Cell(x, y) = value;
327 }
328 }
329 double solution_count = nl.Solve();
330 printf("# of solutions: ");
331 // Change an output format because of the precision of the double type
332 if (solution_count < 1e13) {
333 printf("%.0f\n", solution_count);
334 } else {
335 printf("%.13e\n", solution_count);
336 }
337 }
338 return 0;
339}