-
Notifications
You must be signed in to change notification settings - Fork 6
/
filling.c
2216 lines (1938 loc) · 63.9 KB
/
filling.c
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- tab-width: 8; indent-tabs-mode: t -*-
* filling.c: An implementation of the Nikoli game fillomino.
* Copyright (C) 2007 Jonas Kölker. See LICENSE for the license.
*/
/* TODO:
*
* - use a typedef instead of int for numbers on the board
* + replace int with something else (signed short?)
* - the type should be signed (for -board[i] and -SENTINEL)
* - the type should be somewhat big: board[i] = i
* - Using shorts gives us 181x181 puzzles as upper bound.
*
* - in board generation, after having merged regions such that no
* more merges are necessary, try splitting (big) regions.
* + it seems that smaller regions make for better puzzles; see
* for instance the 7x7 puzzle in this file (grep for 7x7:).
*
* - symmetric hints (solo-style)
* + right now that means including _many_ hints, and the puzzles
* won't look any nicer. Not worth it (at the moment).
*
* - make the solver do recursion/backtracking.
* + This is for user-submitted puzzles, not for puzzle
* generation (on the other hand, never say never).
*
* - prove that only w=h=2 needs a special case
*
* - solo-like pencil marks?
*
* - a user says that the difficulty is unevenly distributed.
* + partition into levels? Will they be non-crap?
*
* - Allow square contents > 9?
* + I could use letters for digits (solo does this), but
* letters don't have numeric significance (normal people hate
* base36), which is relevant here (much more than in solo).
* + [click, 1, 0, enter] => [10 in clicked square]?
* + How much information is needed to solve? Does one need to
* know the algorithm by which the largest number is set?
*
* - eliminate puzzle instances with done chunks (1's in particular)?
* + that's what the qsort call is all about.
* + the 1's don't bother me that much.
* + but this takes a LONG time (not always possible)?
* - this may be affected by solver (lack of) quality.
* - weed them out by construction instead of post-cons check
* + but that interleaves make_board and new_game_desc: you
* have to alternate between changing the board and
* changing the hint set (instead of just creating the
* board once, then changing the hint set once -> done).
*
* - use binary search when discovering the minimal sovable point
* + profile to show a need (but when the solver gets slower...)
* + 7x9 @ .011s, 9x13 @ .075s, 17x13 @ .661s (all avg with n=100)
* + but the hints are independent, not linear, so... what?
*/
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "puzzles.h"
static bool verbose;
static void printv(const char *fmt, ...) {
#ifndef PALM
if (verbose) {
va_list va;
va_start(va, fmt);
vprintf(fmt, va);
va_end(va);
}
#endif
}
/*****************************************************************************
* GAME CONFIGURATION AND PARAMETERS *
*****************************************************************************/
struct game_params {
int w, h;
};
struct shared_state {
struct game_params params;
int *clues;
int refcnt;
};
struct game_state {
int *board;
struct shared_state *shared;
bool completed, cheated;
};
static const struct game_params filling_defaults[3] = {
{9, 7}, {13, 9}, {17, 13}
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
*ret = filling_defaults[1]; /* struct copy */
return ret;
}
static bool game_fetch_preset(int i, char **name, game_params **params)
{
char buf[64];
if (i < 0 || i >= lenof(filling_defaults)) return false;
*params = snew(game_params);
**params = filling_defaults[i]; /* struct copy */
sprintf(buf, "%dx%d", filling_defaults[i].w, filling_defaults[i].h);
*name = dupstr(buf);
return true;
}
static void free_params(game_params *params)
{
sfree(params);
}
static game_params *dup_params(const game_params *params)
{
game_params *ret = snew(game_params);
*ret = *params; /* struct copy */
return ret;
}
static void decode_params(game_params *ret, char const *string)
{
ret->w = ret->h = atoi(string);
while (*string && isdigit((unsigned char) *string)) ++string;
if (*string == 'x') ret->h = atoi(++string);
}
static char *encode_params(const game_params *params, bool full)
{
char buf[64];
sprintf(buf, "%dx%d", params->w, params->h);
return dupstr(buf);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[64];
ret = snewn(3, config_item);
ret[0].name = "Width";
ret[0].type = C_STRING;
sprintf(buf, "%d", params->w);
ret[0].u.string.sval = dupstr(buf);
ret[1].name = "Height";
ret[1].type = C_STRING;
sprintf(buf, "%d", params->h);
ret[1].u.string.sval = dupstr(buf);
ret[2].name = NULL;
ret[2].type = C_END;
return ret;
}
static game_params *custom_params(const config_item *cfg)
{
game_params *ret = snew(game_params);
ret->w = atoi(cfg[0].u.string.sval);
ret->h = atoi(cfg[1].u.string.sval);
return ret;
}
static const char *validate_params(const game_params *params, bool full)
{
if (params->w < 1) return "Width must be at least one";
if (params->h < 1) return "Height must be at least one";
return NULL;
}
/*****************************************************************************
* STRINGIFICATION OF GAME STATE *
*****************************************************************************/
#define EMPTY 0
/* Example of plaintext rendering:
* +---+---+---+---+---+---+---+
* | 6 | | | 2 | | | 2 |
* +---+---+---+---+---+---+---+
* | | 3 | | 6 | | 3 | |
* +---+---+---+---+---+---+---+
* | 3 | | | | | | 1 |
* +---+---+---+---+---+---+---+
* | | 2 | 3 | | 4 | 2 | |
* +---+---+---+---+---+---+---+
* | 2 | | | | | | 3 |
* +---+---+---+---+---+---+---+
* | | 5 | | 1 | | 4 | |
* +---+---+---+---+---+---+---+
* | 4 | | | 3 | | | 3 |
* +---+---+---+---+---+---+---+
*
* This puzzle instance is taken from the nikoli website
* Encoded (unsolved and solved), the strings are these:
* 7x7:6002002030603030000010230420200000305010404003003
* 7x7:6662232336663232331311235422255544325413434443313
*/
static char *board_to_string(int *board, int w, int h) {
const int sz = w * h;
const int chw = (4*w + 2); /* +2 for trailing '+' and '\n' */
const int chh = (2*h + 1); /* +1: n fence segments, n+1 posts */
const int chlen = chw * chh;
char *repr = snewn(chlen + 1, char);
int i;
assert(board);
/* build the first line ("^(\+---){n}\+$") */
for (i = 0; i < w; ++i) {
repr[4*i + 0] = '+';
repr[4*i + 1] = '-';
repr[4*i + 2] = '-';
repr[4*i + 3] = '-';
}
repr[4*i + 0] = '+';
repr[4*i + 1] = '\n';
/* ... and copy it onto the odd-numbered lines */
for (i = 0; i < h; ++i) memcpy(repr + (2*i + 2) * chw, repr, chw);
/* build the second line ("^(\|\t){n}\|$") */
for (i = 0; i < w; ++i) {
repr[chw + 4*i + 0] = '|';
repr[chw + 4*i + 1] = ' ';
repr[chw + 4*i + 2] = ' ';
repr[chw + 4*i + 3] = ' ';
}
repr[chw + 4*i + 0] = '|';
repr[chw + 4*i + 1] = '\n';
/* ... and copy it onto the even-numbered lines */
for (i = 1; i < h; ++i) memcpy(repr + (2*i + 1) * chw, repr + chw, chw);
/* fill in the numbers */
for (i = 0; i < sz; ++i) {
const int x = i % w;
const int y = i / w;
if (board[i] == EMPTY) continue;
repr[chw*(2*y + 1) + (4*x + 2)] = board[i] + '0';
}
repr[chlen] = '\0';
return repr;
}
static bool game_can_format_as_text_now(const game_params *params)
{
return true;
}
static char *game_text_format(const game_state *state)
{
const int w = state->shared->params.w;
const int h = state->shared->params.h;
return board_to_string(state->board, w, h);
}
/*****************************************************************************
* GAME GENERATION AND SOLVER *
*****************************************************************************/
static const int dx[4] = {-1, 1, 0, 0};
static const int dy[4] = {0, 0, -1, 1};
struct solver_state
{
int *dsf;
int *board;
int *connected;
int nempty;
/* Used internally by learn_bitmap_deductions; kept here to avoid
* mallocing/freeing them every time that function is called. */
int *bm, *bmdsf, *bmminsize;
};
static void print_board(int *board, int w, int h) {
if (verbose) {
char *repr = board_to_string(board, w, h);
printv("%s\n", repr);
free(repr);
}
}
static game_state *new_game(midend *, const game_params *, const char *);
static void free_game(game_state *);
#define SENTINEL (sz+1)
static bool mark_region(int *board, int w, int h, int i, int n, int m) {
int j;
board[i] = -1;
for (j = 0; j < 4; ++j) {
const int x = (i % w) + dx[j], y = (i / w) + dy[j], ii = w*y + x;
if (x < 0 || x >= w || y < 0 || y >= h) continue;
if (board[ii] == m) return false;
if (board[ii] != n) continue;
if (!mark_region(board, w, h, ii, n, m)) return false;
}
return true;
}
static int region_size(int *board, int w, int h, int i) {
const int sz = w * h;
int j, size, copy;
if (board[i] == 0) return 0;
copy = board[i];
mark_region(board, w, h, i, board[i], SENTINEL);
for (size = j = 0; j < sz; ++j) {
if (board[j] != -1) continue;
++size;
board[j] = copy;
}
return size;
}
static void merge_ones(int *board, int w, int h)
{
const int sz = w * h;
const int maxsize = min(max(max(w, h), 3), 9);
int i, j, k;
bool change;
do {
change = false;
for (i = 0; i < sz; ++i) {
if (board[i] != 1) continue;
for (j = 0; j < 4; ++j, board[i] = 1) {
const int x = (i % w) + dx[j], y = (i / w) + dy[j];
int oldsize, newsize, ii = w*y + x;
bool ok;
if (x < 0 || x >= w || y < 0 || y >= h) continue;
if (board[ii] == maxsize) continue;
oldsize = board[ii];
board[i] = oldsize;
newsize = region_size(board, w, h, i);
if (newsize > maxsize) continue;
ok = mark_region(board, w, h, i, oldsize, newsize);
for (k = 0; k < sz; ++k)
if (board[k] == -1)
board[k] = ok ? newsize : oldsize;
if (ok) break;
}
if (j < 4) change = true;
}
} while (change);
}
/* generate a random valid board; uses validate_board. */
static void make_board(int *board, int w, int h, random_state *rs) {
const int sz = w * h;
/* w=h=2 is a special case which requires a number > max(w, h) */
/* TODO prove that this is the case ONLY for w=h=2. */
const int maxsize = min(max(max(w, h), 3), 9);
/* Note that if 1 in {w, h} then it's impossible to have a region
* of size > w*h, so the special case only affects w=h=2. */
int i, *dsf;
bool change;
assert(w >= 1);
assert(h >= 1);
assert(board);
/* I abuse the board variable: when generating the puzzle, it
* contains a shuffled list of numbers {0, ..., sz-1}. */
for (i = 0; i < sz; ++i) board[i] = i;
dsf = snewn(sz, int);
retry:
dsf_init(dsf, sz);
shuffle(board, sz, sizeof (int), rs);
do {
change = false; /* as long as the board potentially has errors */
for (i = 0; i < sz; ++i) {
const int square = dsf_canonify(dsf, board[i]);
const int size = dsf_size(dsf, square);
int merge = SENTINEL, min = maxsize - size + 1;
bool error = false;
int neighbour, neighbour_size, j;
int directions[4];
for (j = 0; j < 4; ++j)
directions[j] = j;
shuffle(directions, 4, sizeof(int), rs);
for (j = 0; j < 4; ++j) {
const int x = (board[i] % w) + dx[directions[j]];
const int y = (board[i] / w) + dy[directions[j]];
if (x < 0 || x >= w || y < 0 || y >= h) continue;
neighbour = dsf_canonify(dsf, w*y + x);
if (square == neighbour) continue;
neighbour_size = dsf_size(dsf, neighbour);
if (size == neighbour_size) error = true;
/* find the smallest neighbour to merge with, which
* wouldn't make the region too large. (This is
* guaranteed by the initial value of `min'.) */
if (neighbour_size < min && random_upto(rs, 10)) {
min = neighbour_size;
merge = neighbour;
}
}
/* if this square is not in error, leave it be */
if (!error) continue;
/* if it is, but we can't fix it, retry the whole board.
* Maybe we could fix it by merging the conflicting
* neighbouring region(s) into some of their neighbours,
* but just restarting works out fine. */
if (merge == SENTINEL) goto retry;
/* merge with the smallest neighbouring workable region. */
dsf_merge(dsf, square, merge);
change = true;
}
} while (change);
for (i = 0; i < sz; ++i) board[i] = dsf_size(dsf, i);
merge_ones(board, w, h);
sfree(dsf);
}
static void merge(int *dsf, int *connected, int a, int b) {
int c;
assert(dsf);
assert(connected);
a = dsf_canonify(dsf, a);
b = dsf_canonify(dsf, b);
if (a == b) return;
dsf_merge(dsf, a, b);
c = connected[a];
connected[a] = connected[b];
connected[b] = c;
}
static void *memdup(const void *ptr, size_t len, size_t esz) {
void *dup = smalloc(len * esz);
assert(ptr);
memcpy(dup, ptr, len * esz);
return dup;
}
static void expand(struct solver_state *s, int w, int h, int t, int f) {
int j;
assert(s);
assert(s->board[t] == EMPTY); /* expand to empty square */
assert(s->board[f] != EMPTY); /* expand from non-empty square */
printv(
"learn: expanding %d from (%d, %d) into (%d, %d)\n",
s->board[f], f % w, f / w, t % w, t / w);
s->board[t] = s->board[f];
for (j = 0; j < 4; ++j) {
const int x = (t % w) + dx[j];
const int y = (t / w) + dy[j];
const int idx = w*y + x;
if (x < 0 || x >= w || y < 0 || y >= h) continue;
if (s->board[idx] != s->board[t]) continue;
merge(s->dsf, s->connected, t, idx);
}
--s->nempty;
}
static void clear_count(int *board, int sz) {
int i;
for (i = 0; i < sz; ++i) {
if (board[i] >= 0) continue;
else if (board[i] == -SENTINEL) board[i] = EMPTY;
else board[i] = -board[i];
}
}
static void flood_count(int *board, int w, int h, int i, int n, int *c) {
const int sz = w * h;
int k;
if (board[i] == EMPTY) board[i] = -SENTINEL;
else if (board[i] == n) board[i] = -board[i];
else return;
if (--*c == 0) return;
for (k = 0; k < 4; ++k) {
const int x = (i % w) + dx[k];
const int y = (i / w) + dy[k];
const int idx = w*y + x;
if (x < 0 || x >= w || y < 0 || y >= h) continue;
flood_count(board, w, h, idx, n, c);
if (*c == 0) return;
}
}
static bool check_capacity(int *board, int w, int h, int i) {
int n = board[i];
flood_count(board, w, h, i, board[i], &n);
clear_count(board, w * h);
return n == 0;
}
static int expandsize(const int *board, int *dsf, int w, int h, int i, int n) {
int j;
int nhits = 0;
int hits[4];
int size = 1;
for (j = 0; j < 4; ++j) {
const int x = (i % w) + dx[j];
const int y = (i / w) + dy[j];
const int idx = w*y + x;
int root;
int m;
if (x < 0 || x >= w || y < 0 || y >= h) continue;
if (board[idx] != n) continue;
root = dsf_canonify(dsf, idx);
for (m = 0; m < nhits && root != hits[m]; ++m);
if (m < nhits) continue;
printv("\t (%d, %d) contrib %d to size\n", x, y, dsf[root] >> 2);
size += dsf_size(dsf, root);
assert(dsf_size(dsf, root) >= 1);
hits[nhits++] = root;
}
return size;
}
/*
* +---+---+---+---+---+---+---+
* | 6 | | | 2 | | | 2 |
* +---+---+---+---+---+---+---+
* | | 3 | | 6 | | 3 | |
* +---+---+---+---+---+---+---+
* | 3 | | | | | | 1 |
* +---+---+---+---+---+---+---+
* | | 2 | 3 | | 4 | 2 | |
* +---+---+---+---+---+---+---+
* | 2 | | | | | | 3 |
* +---+---+---+---+---+---+---+
* | | 5 | | 1 | | 4 | |
* +---+---+---+---+---+---+---+
* | 4 | | | 3 | | | 3 |
* +---+---+---+---+---+---+---+
*/
/* Solving techniques:
*
* CONNECTED COMPONENT FORCED EXPANSION (too big):
* When a CC can only be expanded in one direction, because all the
* other ones would make the CC too big.
* +---+---+---+---+---+
* | 2 | 2 | | 2 | _ |
* +---+---+---+---+---+
*
* CONNECTED COMPONENT FORCED EXPANSION (too small):
* When a CC must include a particular square, because otherwise there
* would not be enough room to complete it. This includes squares not
* adjacent to the CC through learn_critical_square.
* +---+---+
* | 2 | _ |
* +---+---+
*
* DROPPING IN A ONE:
* When an empty square has no neighbouring empty squares and only a 1
* will go into the square (or other CCs would be too big).
* +---+---+---+
* | 2 | 2 | _ |
* +---+---+---+
*
* TODO: generalise DROPPING IN A ONE: find the size of the CC of
* empty squares and a list of all adjacent numbers. See if only one
* number in {1, ..., size} u {all adjacent numbers} is possible.
* Probably this is only effective for a CC size < n for some n (4?)
*
* TODO: backtracking.
*/
static void filled_square(struct solver_state *s, int w, int h, int i) {
int j;
for (j = 0; j < 4; ++j) {
const int x = (i % w) + dx[j];
const int y = (i / w) + dy[j];
const int idx = w*y + x;
if (x < 0 || x >= w || y < 0 || y >= h) continue;
if (s->board[i] == s->board[idx])
merge(s->dsf, s->connected, i, idx);
}
}
static void init_solver_state(struct solver_state *s, int w, int h) {
const int sz = w * h;
int i;
assert(s);
s->nempty = 0;
for (i = 0; i < sz; ++i) s->connected[i] = i;
for (i = 0; i < sz; ++i)
if (s->board[i] == EMPTY) ++s->nempty;
else filled_square(s, w, h, i);
}
static bool learn_expand_or_one(struct solver_state *s, int w, int h) {
const int sz = w * h;
int i;
bool learn = false;
assert(s);
for (i = 0; i < sz; ++i) {
int j;
bool one = true;
if (s->board[i] != EMPTY) continue;
for (j = 0; j < 4; ++j) {
const int x = (i % w) + dx[j];
const int y = (i / w) + dy[j];
const int idx = w*y + x;
if (x < 0 || x >= w || y < 0 || y >= h) continue;
if (s->board[idx] == EMPTY) {
one = false;
continue;
}
if (one &&
(s->board[idx] == 1 ||
(s->board[idx] >= expandsize(s->board, s->dsf, w, h,
i, s->board[idx]))))
one = false;
if (dsf_size(s->dsf, idx) == s->board[idx]) continue;
assert(s->board[i] == EMPTY);
s->board[i] = -SENTINEL;
if (check_capacity(s->board, w, h, idx)) continue;
assert(s->board[i] == EMPTY);
printv("learn: expanding in one\n");
expand(s, w, h, i, idx);
learn = true;
break;
}
if (j == 4 && one) {
printv("learn: one at (%d, %d)\n", i % w, i / w);
assert(s->board[i] == EMPTY);
s->board[i] = 1;
assert(s->nempty);
--s->nempty;
learn = true;
}
}
return learn;
}
static bool learn_blocked_expansion(struct solver_state *s, int w, int h) {
const int sz = w * h;
int i;
bool learn = false;
assert(s);
/* for every connected component */
for (i = 0; i < sz; ++i) {
int exp = SENTINEL;
int j;
if (s->board[i] == EMPTY) continue;
j = dsf_canonify(s->dsf, i);
/* (but only for each connected component) */
if (i != j) continue;
/* (and not if it's already complete) */
if (dsf_size(s->dsf, j) == s->board[j]) continue;
/* for each square j _in_ the connected component */
do {
int k;
printv(" looking at (%d, %d)\n", j % w, j / w);
/* for each neighbouring square (idx) */
for (k = 0; k < 4; ++k) {
const int x = (j % w) + dx[k];
const int y = (j / w) + dy[k];
const int idx = w*y + x;
int size;
/* int l;
int nhits = 0;
int hits[4]; */
if (x < 0 || x >= w || y < 0 || y >= h) continue;
if (s->board[idx] != EMPTY) continue;
if (exp == idx) continue;
printv("\ttrying to expand onto (%d, %d)\n", x, y);
/* find out the would-be size of the new connected
* component if we actually expanded into idx */
/*
size = 1;
for (l = 0; l < 4; ++l) {
const int lx = x + dx[l];
const int ly = y + dy[l];
const int idxl = w*ly + lx;
int root;
int m;
if (lx < 0 || lx >= w || ly < 0 || ly >= h) continue;
if (board[idxl] != board[j]) continue;
root = dsf_canonify(dsf, idxl);
for (m = 0; m < nhits && root != hits[m]; ++m);
if (m != nhits) continue;
// printv("\t (%d, %d) contributed %d to size\n", lx, ly, dsf[root] >> 2);
size += dsf_size(dsf, root);
assert(dsf_size(dsf, root) >= 1);
hits[nhits++] = root;
}
*/
size = expandsize(s->board, s->dsf, w, h, idx, s->board[j]);
/* ... and see if that size is too big, or if we
* have other expansion candidates. Otherwise
* remember the (so far) only candidate. */
printv("\tthat would give a size of %d\n", size);
if (size > s->board[j]) continue;
/* printv("\tnow knowing %d expansions\n", nexpand + 1); */
if (exp != SENTINEL) goto next_i;
assert(exp != idx);
exp = idx;
}
j = s->connected[j]; /* next square in the same CC */
assert(s->board[i] == s->board[j]);
} while (j != i);
/* end: for each square j _in_ the connected component */
if (exp == SENTINEL) continue;
printv("learning to expand\n");
expand(s, w, h, exp, i);
learn = true;
next_i:
;
}
/* end: for each connected component */
return learn;
}
static bool learn_critical_square(struct solver_state *s, int w, int h) {
const int sz = w * h;
int i;
bool learn = false;
assert(s);
/* for each connected component */
for (i = 0; i < sz; ++i) {
int j, slack;
if (s->board[i] == EMPTY) continue;
if (i != dsf_canonify(s->dsf, i)) continue;
slack = s->board[i] - dsf_size(s->dsf, i);
if (slack == 0) continue;
assert(s->board[i] != 1);
/* for each empty square */
for (j = 0; j < sz; ++j) {
if (s->board[j] == EMPTY) {
/* if it's too far away from the CC, don't bother */
int k = i, jx = j % w, jy = j / w;
do {
int kx = k % w, ky = k / w;
if (abs(kx - jx) + abs(ky - jy) <= slack) break;
k = s->connected[k];
} while (i != k);
if (i == k) continue; /* not within range */
} else continue;
s->board[j] = -SENTINEL;
if (check_capacity(s->board, w, h, i)) continue;
/* if not expanding s->board[i] to s->board[j] implies
* that s->board[i] can't reach its full size, ... */
assert(s->nempty);
printv(
"learn: ds %d at (%d, %d) blocking (%d, %d)\n",
s->board[i], j % w, j / w, i % w, i / w);
--s->nempty;
s->board[j] = s->board[i];
filled_square(s, w, h, j);
learn = true;
}
}
return learn;
}
#if 0
static void print_bitmap(int *bitmap, int w, int h) {
if (verbose) {
int x, y;
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
printv(" %03x", bm[y*w+x]);
}
printv("\n");
}
}
}
#endif
static bool learn_bitmap_deductions(struct solver_state *s, int w, int h)
{
const int sz = w * h;
int *bm = s->bm;
int *dsf = s->bmdsf;
int *minsize = s->bmminsize;
int x, y, i, j, n;
bool learn = false;
/*
* This function does deductions based on building up a bitmap
* which indicates the possible numbers that can appear in each
* grid square. If we can rule out all but one possibility for a
* particular square, then we've found out the value of that
* square. In particular, this is one of the few forms of
* deduction capable of inferring the existence of a 'ghost
* region', i.e. a region which has none of its squares filled in
* at all.
*
* The reasoning goes like this. A currently unfilled square S can
* turn out to contain digit n in exactly two ways: either S is
* part of an n-region which also includes some currently known
* connected component of squares with n in, or S is part of an
* n-region separate from _all_ currently known connected
* components. If we can rule out both possibilities, then square
* S can't contain digit n at all.
*
* The former possibility: if there's a region of size n
* containing both S and some existing component C, then that
* means the distance from S to C must be small enough that C
* could be extended to include S without becoming too big. So we
* can do a breadth-first search out from all existing components
* with n in them, to identify all the squares which could be
* joined to any of them.
*
* The latter possibility: if there's a region of size n that
* doesn't contain _any_ existing component, then it also can't
* contain any square adjacent to an existing component either. So
* we can identify all the EMPTY squares not adjacent to any
* existing square with n in, and group them into connected
* components; then any component of size less than n is ruled
* out, because there wouldn't be room to create a completely new
* n-region in it.
*
* In fact we process these possibilities in the other order.
* First we find all the squares not adjacent to an existing
* square with n in; then we winnow those by removing too-small
* connected components, to get the set of squares which could
* possibly be part of a brand new n-region; and finally we do the
* breadth-first search to add in the set of squares which could
* possibly be added to some existing n-region.
*/
/*
* Start by initialising our bitmap to 'all numbers possible in
* all squares'.
*/
for (y = 0; y < h; y++)
for (x = 0; x < w; x++)
bm[y*w+x] = (1 << 10) - (1 << 1); /* bits 1,2,...,9 now set */
#if 0
printv("initial bitmap:\n");
print_bitmap(bm, w, h);
#endif
/*
* Now completely zero out the bitmap for squares that are already
* filled in (we aren't interested in those anyway). Also, for any
* filled square, eliminate its number from all its neighbours
* (because, as discussed above, the neighbours couldn't be part
* of a _new_ region with that number in it, and that's the case
* we consider first).
*/
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
i = y*w+x;
n = s->board[i];
if (n != EMPTY) {
bm[i] = 0;
if (x > 0)
bm[i-1] &= ~(1 << n);
if (x+1 < w)
bm[i+1] &= ~(1 << n);
if (y > 0)
bm[i-w] &= ~(1 << n);
if (y+1 < h)
bm[i+w] &= ~(1 << n);
}
}
}
#if 0
printv("bitmap after filled squares:\n");
print_bitmap(bm, w, h);
#endif
/*
* Now, for each n, we separately find the connected components of
* squares for which n is still a possibility. Then discard any
* component of size < n, because that component is too small to
* have a completely new n-region in it.
*/
for (n = 1; n <= 9; n++) {
dsf_init(dsf, sz);
/* Build the dsf */
for (y = 0; y < h; y++)
for (x = 0; x+1 < w; x++)
if (bm[y*w+x] & bm[y*w+(x+1)] & (1 << n))
dsf_merge(dsf, y*w+x, y*w+(x+1));
for (y = 0; y+1 < h; y++)
for (x = 0; x < w; x++)
if (bm[y*w+x] & bm[(y+1)*w+x] & (1 << n))
dsf_merge(dsf, y*w+x, (y+1)*w+x);
/* Query the dsf */
for (i = 0; i < sz; i++)
if ((bm[i] & (1 << n)) && dsf_size(dsf, i) < n)
bm[i] &= ~(1 << n);
}
#if 0
printv("bitmap after winnowing small components:\n");
print_bitmap(bm, w, h);
#endif
/*
* Now our bitmap includes every square which could be part of a
* completely new region, of any size. Extend it to include
* squares which could be part of an existing region.
*/
for (n = 1; n <= 9; n++) {
/*
* We're going to do a breadth-first search starting from
* existing connected components with cell value n, to find
* all cells they might possibly extend into.
*
* The quantity we compute, for each square, is 'minimum size
* that any existing CC would have to have if extended to
* include this square'. So squares already _in_ an existing
* CC are initialised to the size of that CC; then we search
* outwards using the rule that if a square's score is j, then
* its neighbours can't score more than j+1.
*
* Scores are capped at n+1, because if a square scores more
* than n then that's enough to know it can't possibly be
* reached by extending an existing region - we don't need to
* know exactly _how far_ out of reach it is.
*/
for (i = 0; i < sz; i++) {
if (s->board[i] == n) {
/* Square is part of an existing CC. */
minsize[i] = dsf_size(s->dsf, i);
} else {
/* Otherwise, initialise to the maximum score n+1;
* we'll reduce this later if we find a neighbouring
* square with a lower score. */
minsize[i] = n+1;
}
}
for (j = 1; j < n; j++) {
/*
* Find neighbours of cells scoring j, and set their score