-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.c
3340 lines (2903 loc) · 88.7 KB
/
map.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
/*
* map.c: Game involving four-colouring a map.
*/
/*
* TODO:
*
* - clue marking
* - better four-colouring algorithm?
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include "puzzles.h"
/*
* In standalone solver mode, `verbose' is a variable which can be
* set by command-line option; in debugging mode it's simply always
* true.
*/
#if defined STANDALONE_SOLVER
#define SOLVER_DIAGNOSTICS
int verbose = FALSE;
#elif defined SOLVER_DIAGNOSTICS
#define verbose TRUE
#endif
/*
* I don't seriously anticipate wanting to change the number of
* colours used in this game, but it doesn't cost much to use a
* #define just in case :-)
*/
#define FOUR 4
#define THREE (FOUR-1)
#define FIVE (FOUR+1)
#define SIX (FOUR+2)
/*
* Ghastly run-time configuration option, just for Gareth (again).
*/
static int flash_type = -1;
static float flash_length;
/*
* Difficulty levels. I do some macro ickery here to ensure that my
* enum and the various forms of my name list always match up.
*/
#define DIFFLIST(A) \
A(EASY,Easy,e) \
A(NORMAL,Normal,n) \
A(HARD,Hard,h) \
A(RECURSE,Unreasonable,u)
#define ENUM(upper,title,lower) DIFF_ ## upper,
#define TITLE(upper,title,lower) #title,
#define ENCODE(upper,title,lower) #lower
#define CONFIG(upper,title,lower) ":" #title
enum { DIFFLIST(ENUM) DIFFCOUNT };
static char const *const map_diffnames[] = { DIFFLIST(TITLE) };
static char const map_diffchars[] = DIFFLIST(ENCODE);
#define DIFFCONFIG DIFFLIST(CONFIG)
enum { TE, BE, LE, RE }; /* top/bottom/left/right edges */
enum {
COL_BACKGROUND,
COL_GRID,
COL_0, COL_1, COL_2, COL_3,
COL_ERROR, COL_ERRTEXT,
NCOLOURS
};
struct game_params {
int w, h, n, diff;
};
struct map {
int refcount;
int *map;
int *graph;
int n;
int ngraph;
int *immutable;
int *edgex, *edgey; /* position of a point on each edge */
int *regionx, *regiony; /* position of a point in each region */
};
struct game_state {
game_params p;
struct map *map;
int *colouring, *pencil;
int completed, cheated;
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
#ifdef PORTRAIT_SCREEN
ret->w = 16;
ret->h = 18;
#else
ret->w = 20;
ret->h = 15;
#endif
ret->n = 30;
ret->diff = DIFF_NORMAL;
return ret;
}
static const struct game_params map_presets[] = {
#ifdef PORTRAIT_SCREEN
{16, 18, 30, DIFF_EASY},
{16, 18, 30, DIFF_NORMAL},
{16, 18, 30, DIFF_HARD},
{16, 18, 30, DIFF_RECURSE},
{25, 30, 75, DIFF_NORMAL},
{25, 30, 75, DIFF_HARD},
#else
{20, 15, 30, DIFF_EASY},
{20, 15, 30, DIFF_NORMAL},
{20, 15, 30, DIFF_HARD},
{20, 15, 30, DIFF_RECURSE},
{30, 25, 75, DIFF_NORMAL},
{30, 25, 75, DIFF_HARD},
#endif
};
static int game_fetch_preset(int i, char **name, game_params **params)
{
game_params *ret;
char str[80];
if (i < 0 || i >= lenof(map_presets))
return FALSE;
ret = snew(game_params);
*ret = map_presets[i];
sprintf(str, "%dx%d, %d regions, %s", ret->w, ret->h, ret->n,
map_diffnames[ret->diff]);
*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 {
params->n = params->w * params->h / 8;
}
if (*p == 'd') {
int i;
p++;
for (i = 0; i < DIFFCOUNT; i++)
if (*p == map_diffchars[i])
params->diff = i;
if (*p) p++;
}
}
static char *encode_params(const game_params *params, int full)
{
char ret[400];
sprintf(ret, "%dx%dn%d", params->w, params->h, params->n);
if (full)
sprintf(ret + strlen(ret), "d%c", map_diffchars[params->diff]);
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].sval = dupstr(buf);
ret[0].ival = 0;
ret[1].name = "Height";
ret[1].type = C_STRING;
sprintf(buf, "%d", params->h);
ret[1].sval = dupstr(buf);
ret[1].ival = 0;
ret[2].name = "Regions";
ret[2].type = C_STRING;
sprintf(buf, "%d", params->n);
ret[2].sval = dupstr(buf);
ret[2].ival = 0;
ret[3].name = "Difficulty";
ret[3].type = C_CHOICES;
ret[3].sval = DIFFCONFIG;
ret[3].ival = params->diff;
ret[4].name = NULL;
ret[4].type = C_END;
ret[4].sval = NULL;
ret[4].ival = 0;
return ret;
}
static game_params *custom_params(const config_item *cfg)
{
game_params *ret = snew(game_params);
ret->w = atoi(cfg[0].sval);
ret->h = atoi(cfg[1].sval);
ret->n = atoi(cfg[2].sval);
ret->diff = cfg[3].ival;
return ret;
}
static char *validate_params(const game_params *params, int full)
{
if (params->w < 2 || params->h < 2)
return "Width and height must be at least two";
if (params->n < 5)
return "Must have at least five regions";
if (params->n > params->w * params->h)
return "Too many regions to fit in grid";
return NULL;
}
/* ----------------------------------------------------------------------
* Cumulative frequency table functions.
*/
/*
* Initialise a cumulative frequency table. (Hardly worth writing
* this function; all it does is to initialise everything in the
* array to zero.)
*/
static void cf_init(int *table, int n)
{
int i;
for (i = 0; i < n; i++)
table[i] = 0;
}
/*
* Increment the count of symbol `sym' by `count'.
*/
static void cf_add(int *table, int n, int sym, int count)
{
int bit;
bit = 1;
while (sym != 0) {
if (sym & bit) {
table[sym] += count;
sym &= ~bit;
}
bit <<= 1;
}
table[0] += count;
}
/*
* Cumulative frequency lookup: return the total count of symbols
* with value less than `sym'.
*/
static int cf_clookup(int *table, int n, int sym)
{
int bit, index, limit, count;
if (sym == 0)
return 0;
assert(0 < sym && sym <= n);
count = table[0]; /* start with the whole table size */
bit = 1;
while (bit < n)
bit <<= 1;
limit = n;
while (bit > 0) {
/*
* Find the least number with its lowest set bit in this
* position which is greater than or equal to sym.
*/
index = ((sym + bit - 1) &~ (bit * 2 - 1)) + bit;
if (index < limit) {
count -= table[index];
limit = index;
}
bit >>= 1;
}
return count;
}
/*
* Single frequency lookup: return the count of symbol `sym'.
*/
static int cf_slookup(int *table, int n, int sym)
{
int count, bit;
assert(0 <= sym && sym < n);
count = table[sym];
for (bit = 1; sym+bit < n && !(sym & bit); bit <<= 1)
count -= table[sym+bit];
return count;
}
/*
* Return the largest symbol index such that the cumulative
* frequency up to that symbol is less than _or equal to_ count.
*/
static int cf_whichsym(int *table, int n, int count) {
int bit, sym, top;
assert(count >= 0 && count < table[0]);
bit = 1;
while (bit < n)
bit <<= 1;
sym = 0;
top = table[0];
while (bit > 0) {
if (sym+bit < n) {
if (count >= top - table[sym+bit])
sym += bit;
else
top -= table[sym+bit];
}
bit >>= 1;
}
return sym;
}
/* ----------------------------------------------------------------------
* Map generation.
*
* FIXME: this isn't entirely optimal at present, because it
* inherently prioritises growing the largest region since there
* are more squares adjacent to it. This acts as a destabilising
* influence leading to a few large regions and mostly small ones.
* It might be better to do it some other way.
*/
#define WEIGHT_INCREASED 2 /* for increased perimeter */
#define WEIGHT_DECREASED 4 /* for decreased perimeter */
#define WEIGHT_UNCHANGED 3 /* for unchanged perimeter */
/*
* Look at a square and decide which colours can be extended into
* it.
*
* If called with index < 0, it adds together one of
* WEIGHT_INCREASED, WEIGHT_DECREASED or WEIGHT_UNCHANGED for each
* colour that has a valid extension (according to the effect that
* it would have on the perimeter of the region being extended) and
* returns the overall total.
*
* If called with index >= 0, it returns one of the possible
* colours depending on the value of index, in such a way that the
* number of possible inputs which would give rise to a given
* return value correspond to the weight of that value.
*/
static int extend_options(int w, int h, int n, int *map,
int x, int y, int index)
{
int c, i, dx, dy;
int col[8];
int total = 0;
if (map[y*w+x] >= 0) {
assert(index < 0);
return 0; /* can't do this square at all */
}
/*
* Fetch the eight neighbours of this square, in order around
* the square.
*/
for (dy = -1; dy <= +1; dy++)
for (dx = -1; dx <= +1; dx++) {
int index = (dy < 0 ? 6-dx : dy > 0 ? 2+dx : 2*(1+dx));
if (x+dx >= 0 && x+dx < w && y+dy >= 0 && y+dy < h)
col[index] = map[(y+dy)*w+(x+dx)];
else
col[index] = -1;
}
/*
* Iterate over each colour that might be feasible.
*
* FIXME: this routine currently has O(n) running time. We
* could turn it into O(FOUR) by only bothering to iterate over
* the colours mentioned in the four neighbouring squares.
*/
for (c = 0; c < n; c++) {
int count, neighbours, runs;
/*
* One of the even indices of col (representing the
* orthogonal neighbours of this square) must be equal to
* c, or else this square is not adjacent to region c and
* obviously cannot become an extension of it at this time.
*/
neighbours = 0;
for (i = 0; i < 8; i += 2)
if (col[i] == c)
neighbours++;
if (!neighbours)
continue;
/*
* Now we know this square is adjacent to region c. The
* next question is, would extending it cause the region to
* become non-simply-connected? If so, we mustn't do it.
*
* We determine this by looking around col to see if we can
* find more than one separate run of colour c.
*/
runs = 0;
for (i = 0; i < 8; i++)
if (col[i] == c && col[(i+1) & 7] != c)
runs++;
if (runs > 1)
continue;
assert(runs == 1);
/*
* This square is a possibility. Determine its effect on
* the region's perimeter (computed from the number of
* orthogonal neighbours - 1 means a perimeter increase, 3
* a decrease, 2 no change; 4 is impossible because the
* region would already not be simply connected) and we're
* done.
*/
assert(neighbours > 0 && neighbours < 4);
count = (neighbours == 1 ? WEIGHT_INCREASED :
neighbours == 2 ? WEIGHT_UNCHANGED : WEIGHT_DECREASED);
total += count;
if (index >= 0 && index < count)
return c;
else
index -= count;
}
assert(index < 0);
return total;
}
static void genmap(int w, int h, int n, int *map, random_state *rs)
{
int wh = w*h;
int x, y, i, k;
int *tmp;
assert(n <= wh);
tmp = snewn(wh, int);
/*
* Clear the map, and set up `tmp' as a list of grid indices.
*/
for (i = 0; i < wh; i++) {
map[i] = -1;
tmp[i] = i;
}
/*
* Place the region seeds by selecting n members from `tmp'.
*/
k = wh;
for (i = 0; i < n; i++) {
int j = random_upto(rs, k);
map[tmp[j]] = i;
tmp[j] = tmp[--k];
}
/*
* Re-initialise `tmp' as a cumulative frequency table. This
* will store the number of possible region colours we can
* extend into each square.
*/
cf_init(tmp, wh);
/*
* Go through the grid and set up the initial cumulative
* frequencies.
*/
for (y = 0; y < h; y++)
for (x = 0; x < w; x++)
cf_add(tmp, wh, y*w+x,
extend_options(w, h, n, map, x, y, -1));
/*
* Now repeatedly choose a square we can extend a region into,
* and do so.
*/
while (tmp[0] > 0) {
int k = random_upto(rs, tmp[0]);
int sq;
int colour;
int xx, yy;
sq = cf_whichsym(tmp, wh, k);
k -= cf_clookup(tmp, wh, sq);
x = sq % w;
y = sq / w;
colour = extend_options(w, h, n, map, x, y, k);
map[sq] = colour;
/*
* Re-scan the nine cells around the one we've just
* modified.
*/
for (yy = max(y-1, 0); yy < min(y+2, h); yy++)
for (xx = max(x-1, 0); xx < min(x+2, w); xx++) {
cf_add(tmp, wh, yy*w+xx,
-cf_slookup(tmp, wh, yy*w+xx) +
extend_options(w, h, n, map, xx, yy, -1));
}
}
/*
* Finally, go through and normalise the region labels into
* order, meaning that indistinguishable maps are actually
* identical.
*/
for (i = 0; i < n; i++)
tmp[i] = -1;
k = 0;
for (i = 0; i < wh; i++) {
assert(map[i] >= 0);
if (tmp[map[i]] < 0)
tmp[map[i]] = k++;
map[i] = tmp[map[i]];
}
sfree(tmp);
}
/* ----------------------------------------------------------------------
* Functions to handle graphs.
*/
/*
* Having got a map in a square grid, convert it into a graph
* representation.
*/
static int gengraph(int w, int h, int n, int *map, int *graph)
{
int i, j, x, y;
/*
* Start by setting the graph up as an adjacency matrix. We'll
* turn it into a list later.
*/
for (i = 0; i < n*n; i++)
graph[i] = 0;
/*
* Iterate over the map looking for all adjacencies.
*/
for (y = 0; y < h; y++)
for (x = 0; x < w; x++) {
int v, vx, vy;
v = map[y*w+x];
if (x+1 < w && (vx = map[y*w+(x+1)]) != v)
graph[v*n+vx] = graph[vx*n+v] = 1;
if (y+1 < h && (vy = map[(y+1)*w+x]) != v)
graph[v*n+vy] = graph[vy*n+v] = 1;
}
/*
* Turn the matrix into a list.
*/
for (i = j = 0; i < n*n; i++)
if (graph[i])
graph[j++] = i;
return j;
}
static int graph_edge_index(int *graph, int n, int ngraph, int i, int j)
{
int v = i*n+j;
int top, bot, mid;
bot = -1;
top = ngraph;
while (top - bot > 1) {
mid = (top + bot) / 2;
if (graph[mid] == v)
return mid;
else if (graph[mid] < v)
bot = mid;
else
top = mid;
}
return -1;
}
#define graph_adjacent(graph, n, ngraph, i, j) \
(graph_edge_index((graph), (n), (ngraph), (i), (j)) >= 0)
static int graph_vertex_start(int *graph, int n, int ngraph, int i)
{
int v = i*n;
int top, bot, mid;
bot = -1;
top = ngraph;
while (top - bot > 1) {
mid = (top + bot) / 2;
if (graph[mid] < v)
bot = mid;
else
top = mid;
}
return top;
}
/* ----------------------------------------------------------------------
* Generate a four-colouring of a graph.
*
* FIXME: it would be nice if we could convert this recursion into
* pseudo-recursion using some sort of explicit stack array, for
* the sake of the Palm port and its limited stack.
*/
static int fourcolour_recurse(int *graph, int n, int ngraph,
int *colouring, int *scratch, random_state *rs)
{
int nfree, nvert, start, i, j, k, c, ci;
int cs[FOUR];
/*
* Find the smallest number of free colours in any uncoloured
* vertex, and count the number of such vertices.
*/
nfree = FIVE; /* start off bigger than FOUR! */
nvert = 0;
for (i = 0; i < n; i++)
if (colouring[i] < 0 && scratch[i*FIVE+FOUR] <= nfree) {
if (nfree > scratch[i*FIVE+FOUR]) {
nfree = scratch[i*FIVE+FOUR];
nvert = 0;
}
nvert++;
}
/*
* If there aren't any uncoloured vertices at all, we're done.
*/
if (nvert == 0)
return TRUE; /* we've got a colouring! */
/*
* Pick a random vertex in that set.
*/
j = random_upto(rs, nvert);
for (i = 0; i < n; i++)
if (colouring[i] < 0 && scratch[i*FIVE+FOUR] == nfree)
if (j-- == 0)
break;
assert(i < n);
start = graph_vertex_start(graph, n, ngraph, i);
/*
* Loop over the possible colours for i, and recurse for each
* one.
*/
ci = 0;
for (c = 0; c < FOUR; c++)
if (scratch[i*FIVE+c] == 0)
cs[ci++] = c;
shuffle(cs, ci, sizeof(*cs), rs);
while (ci-- > 0) {
c = cs[ci];
/*
* Fill in this colour.
*/
colouring[i] = c;
/*
* Update the scratch space to reflect a new neighbour
* of this colour for each neighbour of vertex i.
*/
for (j = start; j < ngraph && graph[j] < n*(i+1); j++) {
k = graph[j] - i*n;
if (scratch[k*FIVE+c] == 0)
scratch[k*FIVE+FOUR]--;
scratch[k*FIVE+c]++;
}
/*
* Recurse.
*/
if (fourcolour_recurse(graph, n, ngraph, colouring, scratch, rs))
return TRUE; /* got one! */
/*
* If that didn't work, clean up and try again with a
* different colour.
*/
for (j = start; j < ngraph && graph[j] < n*(i+1); j++) {
k = graph[j] - i*n;
scratch[k*FIVE+c]--;
if (scratch[k*FIVE+c] == 0)
scratch[k*FIVE+FOUR]++;
}
colouring[i] = -1;
}
/*
* If we reach here, we were unable to find a colouring at all.
* (This doesn't necessarily mean the Four Colour Theorem is
* violated; it might just mean we've gone down a dead end and
* need to back up and look somewhere else. It's only an FCT
* violation if we get all the way back up to the top level and
* still fail.)
*/
return FALSE;
}
static void fourcolour(int *graph, int n, int ngraph, int *colouring,
random_state *rs)
{
int *scratch;
int i;
/*
* For each vertex and each colour, we store the number of
* neighbours that have that colour. Also, we store the number
* of free colours for the vertex.
*/
scratch = snewn(n * FIVE, int);
for (i = 0; i < n * FIVE; i++)
scratch[i] = (i % FIVE == FOUR ? FOUR : 0);
/*
* Clear the colouring to start with.
*/
for (i = 0; i < n; i++)
colouring[i] = -1;
i = fourcolour_recurse(graph, n, ngraph, colouring, scratch, rs);
assert(i); /* by the Four Colour Theorem :-) */
sfree(scratch);
}
/* ----------------------------------------------------------------------
* Non-recursive solver.
*/
struct solver_scratch {
unsigned char *possible; /* bitmap of colours for each region */
int *graph;
int n;
int ngraph;
int *bfsqueue;
int *bfscolour;
#ifdef SOLVER_DIAGNOSTICS
int *bfsprev;
#endif
int depth;
};
static struct solver_scratch *new_scratch(int *graph, int n, int ngraph)
{
struct solver_scratch *sc;
sc = snew(struct solver_scratch);
sc->graph = graph;
sc->n = n;
sc->ngraph = ngraph;
sc->possible = snewn(n, unsigned char);
sc->depth = 0;
sc->bfsqueue = snewn(n, int);
sc->bfscolour = snewn(n, int);
#ifdef SOLVER_DIAGNOSTICS
sc->bfsprev = snewn(n, int);
#endif
return sc;
}
static void free_scratch(struct solver_scratch *sc)
{
sfree(sc->possible);
sfree(sc->bfsqueue);
sfree(sc->bfscolour);
#ifdef SOLVER_DIAGNOSTICS
sfree(sc->bfsprev);
#endif
sfree(sc);
}
/*
* Count the bits in a word. Only needs to cope with FOUR bits.
*/
static int bitcount(int word)
{
assert(FOUR <= 4); /* or this needs changing */
word = ((word & 0xA) >> 1) + (word & 0x5);
word = ((word & 0xC) >> 2) + (word & 0x3);
return word;
}
#ifdef SOLVER_DIAGNOSTICS
static const char colnames[FOUR] = { 'R', 'Y', 'G', 'B' };
#endif
static int place_colour(struct solver_scratch *sc,
int *colouring, int index, int colour
#ifdef SOLVER_DIAGNOSTICS
, char *verb
#endif
)
{
int *graph = sc->graph, n = sc->n, ngraph = sc->ngraph;
int j, k;
if (!(sc->possible[index] & (1 << colour))) {
#ifdef SOLVER_DIAGNOSTICS
if (verbose)
printf("%*scannot place %c in region %d\n", 2*sc->depth, "",
colnames[colour], index);
#endif
return FALSE; /* can't do it */
}
sc->possible[index] = 1 << colour;
colouring[index] = colour;
#ifdef SOLVER_DIAGNOSTICS
if (verbose)
printf("%*s%s %c in region %d\n", 2*sc->depth, "",
verb, colnames[colour], index);
#endif
/*
* Rule out this colour from all the region's neighbours.
*/
for (j = graph_vertex_start(graph, n, ngraph, index);
j < ngraph && graph[j] < n*(index+1); j++) {
k = graph[j] - index*n;
#ifdef SOLVER_DIAGNOSTICS
if (verbose && (sc->possible[k] & (1 << colour)))
printf("%*s ruling out %c in region %d\n", 2*sc->depth, "",
colnames[colour], k);
#endif
sc->possible[k] &= ~(1 << colour);
}
return TRUE;
}
#ifdef SOLVER_DIAGNOSTICS
static char *colourset(char *buf, int set)
{
int i;
char *p = buf;
char *sep = "";
for (i = 0; i < FOUR; i++)
if (set & (1 << i)) {
p += sprintf(p, "%s%c", sep, colnames[i]);
sep = ",";
}
return buf;
}
#endif
/*
* Returns 0 for impossible, 1 for success, 2 for failure to
* converge (i.e. puzzle is either ambiguous or just too
* difficult).
*/
static int map_solver(struct solver_scratch *sc,
int *graph, int n, int ngraph, int *colouring,
int difficulty)
{
int i;
if (sc->depth == 0) {
/*
* Initialise scratch space.
*/
for (i = 0; i < n; i++)
sc->possible[i] = (1 << FOUR) - 1;
/*
* Place clues.
*/
for (i = 0; i < n; i++)
if (colouring[i] >= 0) {
if (!place_colour(sc, colouring, i, colouring[i]
#ifdef SOLVER_DIAGNOSTICS
, "initial clue:"
#endif
)) {
#ifdef SOLVER_DIAGNOSTICS
if (verbose)
printf("%*sinitial clue set is inconsistent\n",
2*sc->depth, "");
#endif
return 0; /* the clues aren't even consistent! */
}
}
}
/*
* Now repeatedly loop until we find nothing further to do.
*/
while (1) {
int done_something = FALSE;
if (difficulty < DIFF_EASY)
break; /* can't do anything at all! */
/*
* Simplest possible deduction: find a region with only one
* possible colour.
*/
for (i = 0; i < n; i++) if (colouring[i] < 0) {
int p = sc->possible[i];
if (p == 0) {
#ifdef SOLVER_DIAGNOSTICS
if (verbose)
printf("%*sregion %d has no possible colours left\n",
2*sc->depth, "", i);
#endif
return 0; /* puzzle is inconsistent */