-
Notifications
You must be signed in to change notification settings - Fork 1
/
mines.c
3292 lines (2911 loc) · 85.6 KB
/
mines.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
/*
* mines.c: Minesweeper clone with sophisticated grid generation.
*
* Still TODO:
*
* - think about configurably supporting question marks.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#ifdef NO_TGMATH_H
# include <math.h>
#else
# include <tgmath.h>
#endif
#include "tree234.h"
#include "puzzles.h"
enum {
COL_BACKGROUND, COL_BACKGROUND2,
COL_1, COL_2, COL_3, COL_4, COL_5, COL_6, COL_7, COL_8,
COL_MINE, COL_BANG, COL_CROSS, COL_FLAG, COL_FLAGBASE, COL_QUERY,
COL_HIGHLIGHT, COL_LOWLIGHT,
COL_WRONGNUMBER,
COL_CURSOR,
NCOLOURS
};
#define PREFERRED_TILE_SIZE 20
#define TILE_SIZE (ds->tilesize)
#ifdef SMALL_SCREEN
#define BORDER 8
#else
#define BORDER (TILE_SIZE * 3 / 2)
#endif
#define HIGHLIGHT_WIDTH (TILE_SIZE / 10 ? TILE_SIZE / 10 : 1)
#define OUTER_HIGHLIGHT_WIDTH (BORDER / 10 ? BORDER / 10 : 1)
#define COORD(x) ( (x) * TILE_SIZE + BORDER )
#define FROMCOORD(x) ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
#define FLASH_FRAME 0.13F
struct game_params {
int w, h, n;
bool unique;
};
struct mine_layout {
/*
* This structure is shared between all the game_states for a
* given instance of the puzzle, so we reference-count it.
*/
int refcount;
bool *mines;
/*
* If we haven't yet actually generated the mine layout, here's
* all the data we will need to do so.
*/
int n;
bool unique;
random_state *rs;
midend *me; /* to give back the new game desc */
};
struct game_state {
int w, h, n;
bool dead, won, used_solve;
struct mine_layout *layout; /* real mine positions */
signed char *grid; /* player knowledge */
/*
* Each item in the `grid' array is one of the following values:
*
* - 0 to 8 mean the square is open and has a surrounding mine
* count.
*
* - -1 means the square is marked as a mine.
*
* - -2 means the square is unknown.
*
* - -3 means the square is marked with a question mark
* (FIXME: do we even want to bother with this?).
*
* - 64 means the square has had a mine revealed when the game
* was lost.
*
* - 65 means the square had a mine revealed and this was the
* one the player hits.
*
* - 66 means the square has a crossed-out mine because the
* player had incorrectly marked it.
*/
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
ret->w = ret->h = 9;
ret->n = 10;
ret->unique = true;
return ret;
}
static const struct game_params mines_presets[] = {
{9, 9, 10, true},
{9, 9, 35, true},
{16, 16, 40, true},
{16, 16, 99, true},
#ifndef SMALL_SCREEN
{30, 16, 99, true},
{30, 16, 170, true},
#endif
};
static bool game_fetch_preset(int i, char **name, game_params **params)
{
game_params *ret;
char str[80];
if (i < 0 || i >= lenof(mines_presets))
return false;
ret = snew(game_params);
*ret = mines_presets[i];
sprintf(str, "%dx%d, %d mines", ret->w, ret->h, ret->n);
*name = dupstr(str);
*params = ret;
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; /* structure copy */
return ret;
}
static void decode_params(game_params *params, char const *string)
{
char const *p = string;
params->w = atoi(p);
while (*p && isdigit((unsigned char)*p)) p++;
if (*p == 'x') {
p++;
params->h = atoi(p);
while (*p && isdigit((unsigned char)*p)) p++;
} else {
params->h = params->w;
}
if (*p == 'n') {
p++;
params->n = atoi(p);
while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
} else {
if (params->h > 0 && params->w > 0 &&
params->w <= INT_MAX / params->h)
params->n = params->w * params->h / 10;
}
while (*p) {
if (*p == 'a') {
p++;
params->unique = false;
} else
p++; /* skip any other gunk */
}
}
static char *encode_params(const game_params *params, bool full)
{
char ret[400];
int len;
len = sprintf(ret, "%dx%d", params->w, params->h);
/*
* Mine count is a generation-time parameter, since it can be
* deduced from the mine bitmap!
*/
if (full)
len += sprintf(ret+len, "n%d", params->n);
if (full && !params->unique)
ret[len++] = 'a';
assert(len < lenof(ret));
ret[len] = '\0';
return dupstr(ret);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[80];
ret = snewn(5, 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 = "Mines";
ret[2].type = C_STRING;
sprintf(buf, "%d", params->n);
ret[2].u.string.sval = dupstr(buf);
ret[3].name = "Ensure solubility";
ret[3].type = C_BOOLEAN;
ret[3].u.boolean.bval = params->unique;
ret[4].name = NULL;
ret[4].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);
ret->n = atoi(cfg[2].u.string.sval);
if (strchr(cfg[2].u.string.sval, '%'))
ret->n = ret->n * (ret->w * ret->h) / 100;
ret->unique = cfg[3].u.boolean.bval;
return ret;
}
static const char *validate_params(const game_params *params, bool full)
{
/*
* Lower limit on grid size: each dimension must be at least 3.
* 1 is theoretically workable if rather boring, but 2 is a
* real problem: there is often _no_ way to generate a uniquely
* solvable 2xn Mines grid. You either run into two mines
* blocking the way and no idea what's behind them, or one mine
* and no way to know which of the two rows it's in. If the
* mine count is even you can create a soluble grid by packing
* all the mines at one end (so that when you hit a two-mine
* wall there are only as many covered squares left as there
* are mines); but if it's odd, you are doomed, because you
* _have_ to have a gap somewhere which you can't determine the
* position of.
*/
if (full && params->unique && (params->w <= 2 || params->h <= 2))
return "Width and height must both be greater than two";
if (params->w < 1 || params->h < 1)
return "Width and height must both be at least one";
if (params->w > SHRT_MAX || params->h > SHRT_MAX)
return "Neither width nor height may be unreasonably large";
/*
* We use random_upto() to place mines, and its maximum limit is 2^28-1.
*/
#if (1<<28)-1 < INT_MAX
if (params->w > ((1<<28)-1) / params->h)
#else
if (params->w > INT_MAX / params->h)
#endif
return "Width times height must not be unreasonably large";
if (params->n < 0)
return "Mine count may not be negative";
if (params->n < 1)
return "Number of mines must be greater than zero";
if (params->n > params->w * params->h - 9)
return "Too many mines for grid size";
/*
* FIXME: Need more constraints here. Not sure what the
* sensible limits for Minesweeper actually are. The limits
* probably ought to change, however, depending on uniqueness.
*/
return NULL;
}
/* ----------------------------------------------------------------------
* Minesweeper solver, used to ensure the generated grids are
* solvable without having to take risks.
*/
/*
* Count the bits in a word. Only needs to cope with 16 bits.
*/
static int bitcount16(int inword)
{
unsigned int word = inword;
word = ((word & 0xAAAA) >> 1) + (word & 0x5555);
word = ((word & 0xCCCC) >> 2) + (word & 0x3333);
word = ((word & 0xF0F0) >> 4) + (word & 0x0F0F);
word = ((word & 0xFF00) >> 8) + (word & 0x00FF);
return (int)word;
}
/*
* We use a tree234 to store a large number of small localised
* sets, each with a mine count. We also keep some of those sets
* linked together into a to-do list.
*/
struct set {
short x, y, mask, mines;
bool todo;
struct set *prev, *next;
};
static int setcmp(void *av, void *bv)
{
struct set *a = (struct set *)av;
struct set *b = (struct set *)bv;
if (a->y < b->y)
return -1;
else if (a->y > b->y)
return +1;
else if (a->x < b->x)
return -1;
else if (a->x > b->x)
return +1;
else if (a->mask < b->mask)
return -1;
else if (a->mask > b->mask)
return +1;
else
return 0;
}
struct setstore {
tree234 *sets;
struct set *todo_head, *todo_tail;
};
static struct setstore *ss_new(void)
{
struct setstore *ss = snew(struct setstore);
ss->sets = newtree234(setcmp);
ss->todo_head = ss->todo_tail = NULL;
return ss;
}
/*
* Take two input sets, in the form (x,y,mask). Munge the first by
* taking either its intersection with the second or its difference
* with the second. Return the new mask part of the first set.
*/
static int setmunge(int x1, int y1, int mask1, int x2, int y2, int mask2,
bool diff)
{
/*
* Adjust the second set so that it has the same x,y
* coordinates as the first.
*/
if (abs(x2-x1) >= 3 || abs(y2-y1) >= 3) {
mask2 = 0;
} else {
while (x2 > x1) {
mask2 &= ~(4|32|256);
mask2 <<= 1;
x2--;
}
while (x2 < x1) {
mask2 &= ~(1|8|64);
mask2 >>= 1;
x2++;
}
while (y2 > y1) {
mask2 &= ~(64|128|256);
mask2 <<= 3;
y2--;
}
while (y2 < y1) {
mask2 &= ~(1|2|4);
mask2 >>= 3;
y2++;
}
}
/*
* Invert the second set if `diff' is set (we're after A &~ B
* rather than A & B).
*/
if (diff)
mask2 ^= 511;
/*
* Now all that's left is a logical AND.
*/
return mask1 & mask2;
}
static void ss_add_todo(struct setstore *ss, struct set *s)
{
if (s->todo)
return; /* already on it */
#ifdef SOLVER_DIAGNOSTICS
printf("adding set on todo list: %d,%d %03x %d\n",
s->x, s->y, s->mask, s->mines);
#endif
s->prev = ss->todo_tail;
if (s->prev)
s->prev->next = s;
else
ss->todo_head = s;
ss->todo_tail = s;
s->next = NULL;
s->todo = true;
}
static void ss_add(struct setstore *ss, int x, int y, int mask, int mines)
{
struct set *s;
assert(mask != 0);
/*
* Normalise so that x and y are genuinely the bounding
* rectangle.
*/
while (!(mask & (1|8|64)))
mask >>= 1, x++;
while (!(mask & (1|2|4)))
mask >>= 3, y++;
/*
* Create a set structure and add it to the tree.
*/
s = snew(struct set);
assert(SHRT_MIN <= x && x <= SHRT_MAX);
s->x = x;
assert(SHRT_MIN <= y && y <= SHRT_MAX);
s->y = y;
s->mask = mask;
s->mines = mines;
s->todo = false;
if (add234(ss->sets, s) != s) {
/*
* This set already existed! Free it and return.
*/
sfree(s);
return;
}
/*
* We've added a new set to the tree, so put it on the todo
* list.
*/
ss_add_todo(ss, s);
}
static void ss_remove(struct setstore *ss, struct set *s)
{
struct set *next = s->next, *prev = s->prev;
#ifdef SOLVER_DIAGNOSTICS
printf("removing set %d,%d %03x\n", s->x, s->y, s->mask);
#endif
/*
* Remove s from the todo list.
*/
if (prev)
prev->next = next;
else if (s == ss->todo_head)
ss->todo_head = next;
if (next)
next->prev = prev;
else if (s == ss->todo_tail)
ss->todo_tail = prev;
s->todo = false;
/*
* Remove s from the tree.
*/
del234(ss->sets, s);
/*
* Destroy the actual set structure.
*/
sfree(s);
}
/*
* Return a dynamically allocated list of all the sets which
* overlap a provided input set.
*/
static struct set **ss_overlap(struct setstore *ss, int x, int y, int mask)
{
struct set **ret = NULL;
int nret = 0, retsize = 0;
int xx, yy;
for (xx = x-3; xx < x+3; xx++)
for (yy = y-3; yy < y+3; yy++) {
struct set stmp, *s;
int pos;
/*
* Find the first set with these top left coordinates.
*/
assert(SHRT_MIN <= xx && xx <= SHRT_MAX);
stmp.x = xx;
assert(SHRT_MIN <= yy && yy <= SHRT_MAX);
stmp.y = yy;
stmp.mask = 0;
if (findrelpos234(ss->sets, &stmp, NULL, REL234_GE, &pos)) {
while ((s = index234(ss->sets, pos)) != NULL &&
s->x == xx && s->y == yy) {
/*
* This set potentially overlaps the input one.
* Compute the intersection to see if they
* really overlap, and add it to the list if
* so.
*/
if (setmunge(x, y, mask, s->x, s->y, s->mask, false)) {
/*
* There's an overlap.
*/
if (nret >= retsize) {
retsize = nret + 32;
ret = sresize(ret, retsize, struct set *);
}
ret[nret++] = s;
}
pos++;
}
}
}
ret = sresize(ret, nret+1, struct set *);
ret[nret] = NULL;
return ret;
}
/*
* Get an element from the head of the set todo list.
*/
static struct set *ss_todo(struct setstore *ss)
{
if (ss->todo_head) {
struct set *ret = ss->todo_head;
ss->todo_head = ret->next;
if (ss->todo_head)
ss->todo_head->prev = NULL;
else
ss->todo_tail = NULL;
ret->next = ret->prev = NULL;
ret->todo = false;
return ret;
} else {
return NULL;
}
}
struct squaretodo {
int *next;
int head, tail;
};
static void std_add(struct squaretodo *std, int i)
{
if (std->tail >= 0)
std->next[std->tail] = i;
else
std->head = i;
std->tail = i;
std->next[i] = -1;
}
typedef int (*open_cb)(void *, int, int);
static void known_squares(int w, int h, struct squaretodo *std,
signed char *grid,
open_cb open, void *openctx,
int x, int y, int mask, bool mine)
{
int xx, yy, bit;
bit = 1;
for (yy = 0; yy < 3; yy++)
for (xx = 0; xx < 3; xx++) {
if (mask & bit) {
int i = (y + yy) * w + (x + xx);
/*
* It's possible that this square is _already_
* known, in which case we don't try to add it to
* the list twice.
*/
if (grid[i] == -2) {
if (mine) {
grid[i] = -1; /* and don't open it! */
} else {
grid[i] = open(openctx, x + xx, y + yy);
assert(grid[i] != -1); /* *bang* */
}
std_add(std, i);
}
}
bit <<= 1;
}
}
/*
* This is data returned from the `perturb' function. It details
* which squares have become mines and which have become clear. The
* solver is (of course) expected to honourably not use that
* knowledge directly, but to efficently adjust its internal data
* structures and proceed based on only the information it
* legitimately has.
*/
struct perturbation {
int x, y;
int delta; /* +1 == become a mine; -1 == cleared */
};
struct perturbations {
int n;
struct perturbation *changes;
};
/*
* Main solver entry point. You give it a grid of existing
* knowledge (-1 for a square known to be a mine, 0-8 for empty
* squares with a given number of neighbours, -2 for completely
* unknown), plus a function which you can call to open new squares
* once you're confident of them. It fills in as much more of the
* grid as it can.
*
* Return value is:
*
* - -1 means deduction stalled and nothing could be done
* - 0 means deduction succeeded fully
* - >0 means deduction succeeded but some number of perturbation
* steps were required; the exact return value is the number of
* perturb calls.
*/
typedef struct perturbations *(*perturb_cb) (void *, signed char *, int, int, int);
static int minesolve(int w, int h, int n, signed char *grid,
open_cb open,
perturb_cb perturb,
void *ctx, random_state *rs)
{
struct setstore *ss = ss_new();
struct set **list;
struct squaretodo astd, *std = &astd;
int x, y, i, j;
int nperturbs = 0;
/*
* Set up a linked list of squares with known contents, so that
* we can process them one by one.
*/
std->next = snewn(w*h, int);
std->head = std->tail = -1;
/*
* Initialise that list with all known squares in the input
* grid.
*/
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
i = y*w+x;
if (grid[i] != -2)
std_add(std, i);
}
}
/*
* Main deductive loop.
*/
while (1) {
bool done_something = false;
struct set *s;
/*
* If there are any known squares on the todo list, process
* them and construct a set for each.
*/
while (std->head != -1) {
i = std->head;
#ifdef SOLVER_DIAGNOSTICS
printf("known square at %d,%d [%d]\n", i%w, i/w, grid[i]);
#endif
std->head = std->next[i];
if (std->head == -1)
std->tail = -1;
x = i % w;
y = i / w;
if (grid[i] >= 0) {
int dx, dy, mines, bit, val;
#ifdef SOLVER_DIAGNOSTICS
printf("creating set around this square\n");
#endif
/*
* Empty square. Construct the set of non-known squares
* around this one, and determine its mine count.
*/
mines = grid[i];
bit = 1;
val = 0;
for (dy = -1; dy <= +1; dy++) {
for (dx = -1; dx <= +1; dx++) {
#ifdef SOLVER_DIAGNOSTICS
printf("grid %d,%d = %d\n", x+dx, y+dy, grid[i+dy*w+dx]);
#endif
if (x+dx < 0 || x+dx >= w || y+dy < 0 || y+dy >= h)
/* ignore this one */;
else if (grid[i+dy*w+dx] == -1)
mines--;
else if (grid[i+dy*w+dx] == -2)
val |= bit;
bit <<= 1;
}
}
if (val)
ss_add(ss, x-1, y-1, val, mines);
}
/*
* Now, whether the square is empty or full, we must
* find any set which contains it and replace it with
* one which does not.
*/
{
#ifdef SOLVER_DIAGNOSTICS
printf("finding sets containing known square %d,%d\n", x, y);
#endif
list = ss_overlap(ss, x, y, 1);
for (j = 0; list[j]; j++) {
int newmask, newmines;
s = list[j];
/*
* Compute the mask for this set minus the
* newly known square.
*/
newmask = setmunge(s->x, s->y, s->mask, x, y, 1, true);
/*
* Compute the new mine count.
*/
newmines = s->mines - (grid[i] == -1);
/*
* Insert the new set into the collection,
* unless it's been whittled right down to
* nothing.
*/
if (newmask)
ss_add(ss, s->x, s->y, newmask, newmines);
/*
* Destroy the old one; it is actually obsolete.
*/
ss_remove(ss, s);
}
sfree(list);
}
/*
* Marking a fresh square as known certainly counts as
* doing something.
*/
done_something = true;
}
/*
* Now pick a set off the to-do list and attempt deductions
* based on it.
*/
if ((s = ss_todo(ss)) != NULL) {
#ifdef SOLVER_DIAGNOSTICS
printf("set to do: %d,%d %03x %d\n", s->x, s->y, s->mask, s->mines);
#endif
/*
* Firstly, see if this set has a mine count of zero or
* of its own cardinality.
*/
if (s->mines == 0 || s->mines == bitcount16(s->mask)) {
/*
* If so, we can immediately mark all the squares
* in the set as known.
*/
#ifdef SOLVER_DIAGNOSTICS
printf("easy\n");
#endif
known_squares(w, h, std, grid, open, ctx,
s->x, s->y, s->mask, (s->mines != 0));
/*
* Having done that, we need do nothing further
* with this set; marking all the squares in it as
* known will eventually eliminate it, and will
* also permit further deductions about anything
* that overlaps it.
*/
continue;
}
/*
* Failing that, we now search through all the sets
* which overlap this one.
*/
list = ss_overlap(ss, s->x, s->y, s->mask);
for (j = 0; list[j]; j++) {
struct set *s2 = list[j];
int swing, s2wing, swc, s2wc;
/*
* Find the non-overlapping parts s2-s and s-s2,
* and their cardinalities.
*
* I'm going to refer to these parts as `wings'
* surrounding the central part common to both
* sets. The `s wing' is s-s2; the `s2 wing' is
* s2-s.
*/
swing = setmunge(s->x, s->y, s->mask, s2->x, s2->y, s2->mask,
true);
s2wing = setmunge(s2->x, s2->y, s2->mask, s->x, s->y, s->mask,
true);
swc = bitcount16(swing);
s2wc = bitcount16(s2wing);
/*
* If one set has more mines than the other, and
* the number of extra mines is equal to the
* cardinality of that set's wing, then we can mark
* every square in the wing as a known mine, and
* every square in the other wing as known clear.
*/
if (swc == s->mines - s2->mines ||
s2wc == s2->mines - s->mines) {
known_squares(w, h, std, grid, open, ctx,
s->x, s->y, swing,
(swc == s->mines - s2->mines));
known_squares(w, h, std, grid, open, ctx,
s2->x, s2->y, s2wing,
(s2wc == s2->mines - s->mines));
continue;
}
/*
* Failing that, see if one set is a subset of the
* other. If so, we can divide up the mine count of
* the larger set between the smaller set and its
* complement, even if neither smaller set ends up
* being immediately clearable.
*/
if (swc == 0 && s2wc != 0) {
/* s is a subset of s2. */
assert(s2->mines > s->mines);
ss_add(ss, s2->x, s2->y, s2wing, s2->mines - s->mines);
} else if (s2wc == 0 && swc != 0) {
/* s2 is a subset of s. */
assert(s->mines > s2->mines);
ss_add(ss, s->x, s->y, swing, s->mines - s2->mines);
}
}
sfree(list);
/*
* In this situation we have definitely done
* _something_, even if it's only reducing the size of
* our to-do list.
*/
done_something = true;
} else if (n >= 0) {
/*
* We have nothing left on our todo list, which means
* all localised deductions have failed. Our next step
* is to resort to global deduction based on the total
* mine count. This is computationally expensive
* compared to any of the above deductions, which is
* why we only ever do it when all else fails, so that
* hopefully it won't have to happen too often.
*
* If you pass n<0 into this solver, that informs it
* that you do not know the total mine count, so it
* won't even attempt these deductions.
*/
int minesleft, squaresleft;
int nsets, cursor;
bool setused[10];
/*
* Start by scanning the current grid state to work out
* how many unknown squares we still have, and how many
* mines are to be placed in them.
*/
squaresleft = 0;
minesleft = n;
for (i = 0; i < w*h; i++) {
if (grid[i] == -1)
minesleft--;
else if (grid[i] == -2)
squaresleft++;
}
#ifdef SOLVER_DIAGNOSTICS
printf("global deduction time: squaresleft=%d minesleft=%d\n",
squaresleft, minesleft);
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
int v = grid[y*w+x];
if (v == -1)
putchar('*');
else if (v == -2)
putchar('?');
else if (v == 0)
putchar('-');
else
putchar('0' + v);
}
putchar('\n');
}
#endif
/*
* If there _are_ no unknown squares, we have actually
* finished.
*/
if (squaresleft == 0) {
assert(minesleft == 0);
break;
}
/*
* First really simple case: if there are no more mines
* left, or if there are exactly as many mines left as
* squares to play them in, then it's all easy.
*/
if (minesleft == 0 || minesleft == squaresleft) {
for (i = 0; i < w*h; i++)
if (grid[i] == -2)
known_squares(w, h, std, grid, open, ctx,
i % w, i / w, 1, minesleft != 0);
continue; /* now go back to main deductive loop */
}
/*
* Failing that, we have to do some _real_ work.
* Ideally what we do here is to try every single
* combination of the currently available sets, in an
* attempt to find a disjoint union (i.e. a set of
* squares with a known mine count between them) such
* that the remaining unknown squares _not_ contained
* in that union either contain no mines or are all
* mines.
*
* Actually enumerating all 2^n possibilities will get
* a bit slow for large n, so I artificially cap this
* recursion at n=10 to avoid too much pain.
*/
nsets = count234(ss->sets);
if (nsets <= lenof(setused)) {
/*
* Doing this with actual recursive function calls
* would get fiddly because a load of local
* variables from this function would have to be
* passed down through the recursion. So instead