02eaf34e6ab858b96276c9add8a30f12eb7afab4
2 * Library code to divide up a rectangle into a number of equally
3 * sized ominoes, in a random fashion.
5 * Could use this for generating solved grids of
6 * http://www.nikoli.co.jp/ja/puzzles/block_puzzle/
7 * or for generating the playfield for Jigsaw Sudoku.
11 * This code is restricted to simply connected solutions: that is,
12 * no single polyomino may completely surround another (not even
13 * with a corner visible to the outside world, in the sense that a
14 * 7-omino can `surround' a single square).
16 * It's tempting to think that this is a natural consequence of
17 * all the ominoes being the same size - after all, a division of
18 * anything into 7-ominoes must necessarily have all of them
19 * simply connected, because if one was not then the 1-square
20 * space in the middle could not be part of any 7-omino - but in
21 * fact, for sufficiently large k, it is perfectly possible for a
22 * k-omino to completely surround another k-omino. A simple
23 * example is this one with two 25-ominoes:
25 * +--+--+--+--+--+--+--+
27 * + +--+--+--+--+--+ +
37 * + +--+--+--+--+--+ +
39 * +--+--+--+--+--+--+--+
41 * I believe the smallest k which can manage this is 23, which I
42 * derive by considering the largest _rectangle_ a k-omino can
43 * surround. Consider: to surround an m x n rectangle, a polyomino
44 * must have 2m squares along the two m-sides of the rectangle, 2n
45 * squares along the n-sides, and fill in three of the corners. So
46 * m+n must be at most (k-3)/2. Hence, to find the largest area of
47 * such a rectangle, we must find m so as to maximise the product
48 * m((k-3)/2-m). This is achieved when m is as close as possible
49 * to half of (k-3)/2; so the largest rectangle surroundable by a
50 * k-omino is equal to floor(k'/2)*ceil(k'/2), with k'=(k-3)/2.
51 * The smallest k for which this is at least k is 23: a 23-omino
52 * can surround a 5x5 rectangle, whereas the best a 22-omino can
55 * (I don't have a definite argument to show that a k-omino cannot
56 * surround a larger area in non-rectangular than rectangular
57 * form, but it seems intuitively obvious to me that it can't. I
58 * may update this with a more rigorous proof if I think of one.)
60 * Anyway: the point is, although constructions of this type are
61 * possible for sufficiently large k, divvy_rectangle() will never
62 * generate them. This could be considered a weakness for some
63 * purposes, in the sense that we can't generate all possible
64 * divisions. However, there are many divisions which we are
65 * highly unlikely to generate anyway, so in practice it probably
68 * If I wanted to fix this issue, I would have to make the rules
69 * more complicated for determining when a square can safely be
70 * _removed_ from a polyomino. Adding one becomes easier (a square
71 * may be added to a polyomino iff it is 4-adjacent to any square
72 * currently part of the polyomino, and the current test for loop
73 * formation may be dispensed with), but to determine which
74 * squares may be removed we must now resort to analysis of the
75 * overall structure of the polyomino rather than the simple local
76 * properties we can currently get away with measuring.
80 * Possible improvements which might cut the fail rate:
82 * - instead of picking one omino to extend in an iteration, try
83 * them all in succession (in a randomised order)
85 * - (for real rigour) instead of bfsing over ominoes, bfs over
86 * the space of possible _removed squares_. That way we aren't
87 * limited to randomly choosing a single square to remove from
88 * an omino and failing if that particular square doesn't
91 * However, I don't currently think it's necessary to do either of
92 * these, because the failure rate is already low enough to be
93 * easily tolerable, under all circumstances I've been able to
105 * Subroutine which implements a function used in computing both
106 * whether a square can safely be added to an omino, and whether
107 * it can safely be removed.
109 * We enumerate the eight squares 8-adjacent to this one, in
110 * cyclic order. We go round that loop and count the number of
111 * times we find a square owned by the target omino next to one
112 * not owned by it. We then return success iff that count is 2.
114 * When adding a square to an omino, this is precisely the
115 * criterion which tells us that adding the square won't leave a
116 * hole in the middle of the omino. (If it did, then things get
117 * more complicated; see above.)
119 * When removing a square from an omino, the _same_ criterion
120 * tells us that removing the square won't disconnect the omino.
121 * (This only works _because_ we've ensured the omino is simply
124 static int addremcommon(int w
, int h
, int x
, int y
, int *own
, int val
)
129 for (dir
= 0; dir
< 8; dir
++) {
130 int dx
= ((dir
& 3) == 2 ?
0 : dir
> 2 && dir
< 6 ?
+1 : -1);
131 int dy
= ((dir
& 3) == 0 ?
0 : dir
< 4 ?
-1 : +1);
132 int sx
= x
+dx
, sy
= y
+dy
;
134 if (sx
< 0 || sx
>= w
|| sy
< 0 || sy
>= h
)
135 neighbours
[dir
] = -1; /* outside the grid */
137 neighbours
[dir
] = own
[sy
*w
+sx
];
141 * To begin with, check 4-adjacency.
143 if (neighbours
[0] != val
&& neighbours
[2] != val
&&
144 neighbours
[4] != val
&& neighbours
[6] != val
)
149 for (dir
= 0; dir
< 8; dir
++) {
150 int next
= (dir
+ 1) & 7;
151 int gotthis
= (neighbours
[dir
] == val
);
152 int gotnext
= (neighbours
[next
] == val
);
154 if (gotthis
!= gotnext
)
162 * w and h are the dimensions of the rectangle.
164 * k is the size of the required ominoes. (So k must divide w*h,
167 * The returned result is a w*h-sized dsf.
169 * In both of the above suggested use cases, the user would
170 * probably want w==h==k, but that isn't a requirement.
172 static int *divvy_internal(int w
, int h
, int k
, random_state
*rs
)
174 int *order
, *queue
, *tmp
, *own
, *sizes
, *addable
, *removable
, *retdsf
;
176 int i
, j
, n
, x
, y
, qhead
, qtail
;
181 order
= snewn(wh
, int);
182 tmp
= snewn(wh
, int);
183 own
= snewn(wh
, int);
184 sizes
= snewn(n
, int);
185 queue
= snewn(n
, int);
186 addable
= snewn(wh
*4, int);
187 removable
= snewn(wh
, int);
190 * Permute the grid squares into a random order, which will be
191 * used for iterating over the grid whenever we need to search
192 * for something. This prevents directional bias and arranges
193 * for the answer to be non-deterministic.
195 for (i
= 0; i
< wh
; i
++)
197 shuffle(order
, wh
, sizeof(*order
), rs
);
200 * Begin by choosing a starting square at random for each
203 for (i
= 0; i
< wh
; i
++) {
206 for (i
= 0; i
< n
; i
++) {
212 * Now repeatedly pick a random omino which isn't already at
213 * the target size, and find a way to expand it by one. This
214 * may involve stealing a square from another omino, in which
215 * case we then re-expand that omino, forming a chain of
216 * square-stealing which terminates in an as yet unclaimed
217 * square. Hence every successful iteration around this loop
218 * causes the number of unclaimed squares to drop by one, and
219 * so the process is bounded in duration.
223 #ifdef DIVVY_DIAGNOSTICS
226 printf("Top of loop. Current grid:\n");
227 for (y
= 0; y
< h
; y
++) {
228 for (x
= 0; x
< w
; x
++)
229 printf("%3d", own
[y
*w
+x
]);
236 * Go over the grid and figure out which squares can
237 * safely be added to, or removed from, each omino. We
238 * don't take account of other ominoes in this process, so
239 * we will often end up knowing that a square can be
240 * poached from one omino by another.
242 * For each square, there may be up to four ominoes to
243 * which it can be added (those to which it is
246 for (y
= 0; y
< h
; y
++) {
247 for (x
= 0; x
< w
; x
++) {
253 removable
[yx
] = FALSE
; /* can't remove if not owned! */
254 } else if (sizes
[curr
] == 1) {
255 removable
[yx
] = TRUE
; /* can always remove a singleton */
258 * See if this square can be removed from its
259 * omino without disconnecting it.
261 removable
[yx
] = addremcommon(w
, h
, x
, y
, own
, curr
);
264 for (dir
= 0; dir
< 4; dir
++) {
265 int dx
= (dir
== 0 ?
-1 : dir
== 1 ?
+1 : 0);
266 int dy
= (dir
== 2 ?
-1 : dir
== 3 ?
+1 : 0);
267 int sx
= x
+ dx
, sy
= y
+ dy
;
270 addable
[yx
*4+dir
] = -1;
272 if (sx
< 0 || sx
>= w
|| sy
< 0 || sy
>= h
)
273 continue; /* no omino here! */
275 continue; /* also no omino here */
276 if (own
[syx
] == own
[yx
])
277 continue; /* we already got one */
278 if (!addremcommon(w
, h
, x
, y
, own
, own
[syx
]))
279 continue; /* would non-simply connect the omino */
281 addable
[yx
*4+dir
] = own
[syx
];
286 for (i
= j
= 0; i
< n
; i
++)
290 break; /* all ominoes are complete! */
291 j
= tmp
[random_upto(rs
, j
)];
292 #ifdef DIVVY_DIAGNOSTICS
293 printf("Trying to extend %d\n", j
);
297 * So we're trying to expand omino j. We breadth-first
298 * search out from j across the space of ominoes.
300 * For bfs purposes, we use two elements of tmp per omino:
301 * tmp[2*i+0] tells us which omino we got to i from, and
302 * tmp[2*i+1] numbers the grid square that omino stole
305 * This requires that wh (the size of tmp) is at least 2n,
306 * i.e. k is at least 2. There would have been nothing to
307 * stop a user calling this function with k=1, but if they
308 * did then we wouldn't have got to _here_ in the code -
309 * we would have noticed above that all ominoes were
310 * already at their target sizes, and terminated :-)
313 for (i
= 0; i
< n
; i
++)
314 tmp
[2*i
] = tmp
[2*i
+1] = -1;
317 tmp
[2*j
] = tmp
[2*j
+1] = -2; /* special value: `starting point' */
319 while (qhead
< qtail
) {
325 * We wish to expand omino j. However, we might have
326 * got here by omino j having a square stolen from it,
327 * so first of all we must temporarily mark that
328 * square as not belonging to j, so that our adjacency
329 * calculations don't assume j _does_ belong to us.
333 assert(own
[tmpsq
] == j
);
338 * OK. Now begin by seeing if we can find any
339 * unclaimed square into which we can expand omino j.
340 * If we find one, the entire bfs terminates.
342 for (i
= 0; i
< wh
; i
++) {
345 if (own
[order
[i
]] != -1)
346 continue; /* this square is claimed */
349 * Special case: if our current omino was size 1
350 * and then had a square stolen from it, it's now
351 * size zero, which means it's valid to `expand'
352 * it into _any_ unclaimed square.
354 if (sizes
[j
] == 1 && tmpsq
>= 0)
358 * Failing that, we must do the full test for
361 for (dir
= 0; dir
< 4; dir
++)
362 if (addable
[order
[i
]*4+dir
] == j
) {
364 * We know this square is addable to this
365 * omino with the grid in the state it had
366 * at the top of the loop. However, we
367 * must now check that it's _still_
368 * addable to this omino when the omino is
369 * missing a square. To do this it's only
370 * necessary to re-check addremcommon.
372 if (!addremcommon(w
, h
, order
[i
]%w
, order
[i
]/w
,
378 continue; /* we can't add this square to j */
380 break; /* got one! */
386 * Restore the temporarily removed square _before_
387 * we start shifting ownerships about.
393 * We are done. We can add square i to omino j,
394 * and then backtrack along the trail in tmp
395 * moving squares between ominoes, ending up
396 * expanding our starting omino by one.
398 #ifdef DIVVY_DIAGNOSTICS
399 printf("(%d,%d)", i
%w
, i
/w
);
403 #ifdef DIVVY_DIAGNOSTICS
410 #ifdef DIVVY_DIAGNOSTICS
411 printf("; (%d,%d)", i
%w
, i
/w
);
414 #ifdef DIVVY_DIAGNOSTICS
419 * Increment the size of the starting omino.
424 * Terminate the bfs loop.
430 * If we get here, we haven't been able to expand
431 * omino j into an unclaimed square. So now we begin
432 * to investigate expanding it into squares which are
433 * claimed by ominoes the bfs has not yet visited.
435 for (i
= 0; i
< wh
; i
++) {
439 if (nj
< 0 || tmp
[2*nj
] != -1)
440 continue; /* unclaimed, or owned by wrong omino */
441 if (!removable
[order
[i
]])
442 continue; /* its omino won't let it go */
444 for (dir
= 0; dir
< 4; dir
++)
445 if (addable
[order
[i
]*4+dir
] == j
) {
447 * As above, re-check addremcommon.
449 if (!addremcommon(w
, h
, order
[i
]%w
, order
[i
]/w
,
454 * We have found a square we can use to
455 * expand omino j, at the expense of the
456 * as-yet unvisited omino nj. So add this
462 tmp
[2*nj
+1] = order
[i
];
465 * Now terminate the loop over dir, to
466 * ensure we don't accidentally add the
467 * same omino twice to the queue.
474 * Restore the temporarily removed square.
480 * Advance the queue head.
485 if (qhead
== qtail
) {
487 * We have finished the bfs and not found any way to
488 * expand omino j. Panic, and return failure.
490 * FIXME: or should we loop over all ominoes before we
493 #ifdef DIVVY_DIAGNOSTICS
501 #ifdef DIVVY_DIAGNOSTICS
504 printf("SUCCESS! Final grid:\n");
505 for (y
= 0; y
< h
; y
++) {
506 for (x
= 0; x
< w
; x
++)
507 printf("%3d", own
[y
*w
+x
]);
514 * Construct the output dsf.
516 for (i
= 0; i
< wh
; i
++) {
517 assert(own
[i
] >= 0 && own
[i
] < n
);
520 retdsf
= snew_dsf(wh
);
521 for (i
= 0; i
< wh
; i
++) {
522 dsf_merge(retdsf
, i
, tmp
[own
[i
]]);
526 * Construct the output dsf a different way, to verify that
527 * the ominoes really are k-ominoes and we haven't
528 * accidentally split one into two disconnected pieces.
531 for (y
= 0; y
< h
; y
++)
532 for (x
= 0; x
+1 < w
; x
++)
533 if (own
[y
*w
+x
] == own
[y
*w
+(x
+1)])
534 dsf_merge(tmp
, y
*w
+x
, y
*w
+(x
+1));
535 for (x
= 0; x
< w
; x
++)
536 for (y
= 0; y
+1 < h
; y
++)
537 if (own
[y
*w
+x
] == own
[(y
+1)*w
+x
])
538 dsf_merge(tmp
, y
*w
+x
, (y
+1)*w
+x
);
539 for (i
= 0; i
< wh
; i
++) {
540 j
= dsf_canonify(retdsf
, i
);
541 assert(dsf_canonify(tmp
, j
) == dsf_canonify(tmp
, i
));
547 * Free our temporary working space.
564 static int fail_counter
= 0;
567 int *divvy_rectangle(int w
, int h
, int k
, random_state
*rs
)
572 ret
= divvy_internal(w
, h
, k
, rs
);
587 * gcc -g -O0 -DTESTMODE -I.. -o divvy divvy.c ../random.c ../malloc.c ../dsf.c ../misc.c ../nullfe.c
591 * gcc -g -O0 -DDIVVY_DIAGNOSTICS -DTESTMODE -I.. -o divvy divvy.c ../random.c ../malloc.c ../dsf.c ../misc.c ../nullfe.c
594 int main(int argc
, char **argv
)
598 int w
= 9, h
= 4, k
= 6, tries
= 100;
601 rs
= random_new("123456", 6);
610 tries
= atoi(argv
[4]);
612 for (i
= 0; i
< tries
; i
++) {
615 dsf
= divvy_rectangle(w
, h
, k
, rs
);
618 for (y
= 0; y
<= 2*h
; y
++) {
619 for (x
= 0; x
<= 2*w
; x
++) {
620 int miny
= y
/2 - 1, maxy
= y
/2;
621 int minx
= x
/2 - 1, maxx
= x
/2;
622 int classes
[4], tx
, ty
;
623 for (ty
= 0; ty
< 2; ty
++)
624 for (tx
= 0; tx
< 2; tx
++) {
625 int cx
= minx
+tx
, cy
= miny
+ty
;
626 if (cx
< 0 || cx
>= w
|| cy
< 0 || cy
>= h
)
627 classes
[ty
*2+tx
] = -1;
629 classes
[ty
*2+tx
] = dsf_canonify(dsf
, cy
*w
+cx
);
631 switch (y
%2 * 2 + x
%2) {
634 * Cases for the corner:
636 * - if all four surrounding squares belong
637 * to the same omino, we print a space.
639 * - if the top two are the same and the
640 * bottom two are the same, we print a
643 * - if the left two are the same and the
644 * right two are the same, we print a
647 * - otherwise, we print a cross.
649 if (classes
[0] == classes
[1] &&
650 classes
[1] == classes
[2] &&
651 classes
[2] == classes
[3])
653 else if (classes
[0] == classes
[1] &&
654 classes
[2] == classes
[3])
656 else if (classes
[0] == classes
[2] &&
657 classes
[1] == classes
[3])
662 case 1: /* horiz edge */
663 if (classes
[1] == classes
[3])
668 case 2: /* vert edge */
669 if (classes
[2] == classes
[3])
674 case 3: /* square centre */
685 printf("%d retries needed for %d successes\n", fail_counter
, tries
);