-
Notifications
You must be signed in to change notification settings - Fork 6
/
tents.c
2735 lines (2459 loc) · 81.7 KB
/
tents.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
/*
* tents.c: Puzzle involving placing tents next to trees subject to
* some confusing conditions.
*
* TODO:
*
* - it might be nice to make setter-provided tent/nontent clues
* inviolable?
* * on the other hand, this would introduce considerable extra
* complexity and size into the game state; also inviolable
* clues would have to be marked as such somehow, in an
* intrusive and annoying manner. Since they're never
* generated by _my_ generator, I'm currently more inclined
* not to bother.
*
* - more difficult levels at the top end?
* * for example, sometimes we can deduce that two BLANKs in
* the same row are each adjacent to the same unattached tree
* and to nothing else, implying that they can't both be
* tents; this enables us to rule out some extra combinations
* in the row-based deduction loop, and hence deduce more
* from the number in that row than we could otherwise do.
* * that by itself doesn't seem worth implementing a new
* difficulty level for, but if I can find a few more things
* like that then it might become worthwhile.
* * I wonder if there's a sensible heuristic for where to
* guess which would make a recursive solver viable?
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include "puzzles.h"
#include "matching.h"
/*
* Design discussion
* -----------------
*
* The rules of this puzzle as available on the WWW are poorly
* specified. The bits about tents having to be orthogonally
* adjacent to trees, tents not being even diagonally adjacent to
* one another, and the number of tents in each row and column
* being given are simple enough; the difficult bit is the
* tent-to-tree matching.
*
* Some sources use simplistic wordings such as `each tree is
* exactly connected to only one tent', which is extremely unclear:
* it's easy to read erroneously as `each tree is _orthogonally
* adjacent_ to exactly one tent', which is definitely incorrect.
* Even the most coherent sources I've found don't do a much better
* job of stating the rule.
*
* A more precise statement of the rule is that it must be possible
* to find a bijection f between tents and trees such that each
* tree T is orthogonally adjacent to the tent f(T), but that a
* tent is permitted to be adjacent to other trees in addition to
* its own. This slightly non-obvious criterion is what gives this
* puzzle most of its subtlety.
*
* However, there's a particularly subtle ambiguity left over. Is
* the bijection between tents and trees required to be _unique_?
* In other words, is that bijection conceptually something the
* player should be able to exhibit as part of the solution (even
* if they aren't actually required to do so)? Or is it sufficient
* to have a unique _placement_ of the tents which gives rise to at
* least one suitable bijection?
*
* The puzzle shown to the right of this .T. 2 *T* 2
* paragraph illustrates the problem. There T.T 0 -> T-T 0
* are two distinct bijections available. .T. 2 *T* 2
* The answer to the above question will
* determine whether it's a valid puzzle. 202 202
*
* This is an important question, because it affects both the
* player and the generator. Eventually I found all the instances
* of this puzzle I could Google up, solved them all by hand, and
* verified that in all cases the tree/tent matching was uniquely
* determined given the tree and tent positions. Therefore, the
* puzzle as implemented in this source file takes the following
* policy:
*
* - When checking a user-supplied solution for correctness, only
* verify that there exists _at least_ one matching.
* - When generating a puzzle, enforce that there must be
* _exactly_ one.
*
* Algorithmic implications
* ------------------------
*
* Another way of phrasing the tree/tent matching criterion is to
* say that the bipartite adjacency graph between trees and tents
* has a perfect matching. That is, if you construct a graph which
* has a vertex per tree and a vertex per tent, and an edge between
* any tree and tent which are orthogonally adjacent, it is
* possible to find a set of N edges of that graph (where N is the
* number of trees and also the number of tents) which between them
* connect every tree to every tent.
*
* The most efficient known algorithms for finding such a matching
* given a graph, as far as I'm aware, are the Munkres assignment
* algorithm (also known as the Hungarian algorithm) and the
* Ford-Fulkerson algorithm (for finding optimal flows in
* networks). Each of these takes O(N^3) running time; so we're
* talking O(N^3) time to verify any candidate solution to this
* puzzle. That's just about OK if you're doing it once per mouse
* click (and in fact not even that, since the sensible thing to do
* is check all the _other_ puzzle criteria and only wade into this
* quagmire if none are violated); but if the solver had to keep
* doing N^3 work internally, then it would probably end up with
* more like N^5 or N^6 running time, and grid generation would
* become very clunky.
*
* Fortunately, I've been able to prove a very useful property of
* _unique_ perfect matchings, by adapting the proof of Hall's
* Marriage Theorem. For those unaware of Hall's Theorem, I'll
* recap it and its proof: it states that a bipartite graph
* contains a perfect matching iff every set of vertices on the
* left side of the graph have a neighbourhood _at least_ as big on
* the right.
*
* This condition is obviously satisfied if a perfect matching does
* exist; each left-side node has a distinct right-side node which
* is the one assigned to it by the matching, and thus any set of n
* left vertices must have a combined neighbourhood containing at
* least the n corresponding right vertices, and possibly others
* too. Alternatively, imagine if you had (say) three left-side
* nodes all of which were connected to only two right-side nodes
* between them: any perfect matching would have to assign one of
* those two right nodes to each of the three left nodes, and still
* give the three left nodes a different right node each. This is
* of course impossible.
*
* To prove the converse (that if every subset of left vertices
* satisfies the Hall condition then a perfect matching exists),
* consider trying to find a proper subset of the left vertices
* which _exactly_ satisfies the Hall condition: that is, its right
* neighbourhood is precisely the same size as it. If we can find
* such a subset, then we can split the bipartite graph into two
* smaller ones: one consisting of the left subset and its right
* neighbourhood, the other consisting of everything else. Edges
* from the left side of the former graph to the right side of the
* latter do not exist, by construction; edges from the right side
* of the former to the left of the latter cannot be part of any
* perfect matching because otherwise the left subset would not be
* left with enough distinct right vertices to connect to (this is
* exactly the same deduction used in Solo's set analysis). You can
* then prove (left as an exercise) that both these smaller graphs
* still satisfy the Hall condition, and therefore the proof will
* follow by induction.
*
* There's one other possibility, which is the case where _no_
* proper subset of the left vertices has a right neighbourhood of
* exactly the same size. That is, every left subset has a strictly
* _larger_ right neighbourhood. In this situation, we can simply
* remove an _arbitrary_ edge from the graph. This cannot reduce
* the size of any left subset's right neighbourhood by more than
* one, so if all neighbourhoods were strictly bigger than they
* needed to be initially, they must now still be _at least as big_
* as they need to be. So we can keep throwing out arbitrary edges
* until we find a set which exactly satisfies the Hall condition,
* and then proceed as above. []
*
* That's Hall's theorem. I now build on this by examining the
* circumstances in which a bipartite graph can have a _unique_
* perfect matching. It is clear that in the second case, where no
* left subset exactly satisfies the Hall condition and so we can
* remove an arbitrary edge, there cannot be a unique perfect
* matching: given one perfect matching, we choose our arbitrary
* removed edge to be one of those contained in it, and then we can
* still find a perfect matching in the remaining graph, which will
* be a distinct perfect matching in the original.
*
* So it is a necessary condition for a unique perfect matching
* that there must be at least one proper left subset which
* _exactly_ satisfies the Hall condition. But now consider the
* smaller graph constructed by taking that left subset and its
* neighbourhood: if the graph as a whole had a unique perfect
* matching, then so must this smaller one, which means we can find
* a proper left subset _again_, and so on. Repeating this process
* must eventually reduce us to a graph with only one left-side
* vertex (so there are no proper subsets at all); this vertex must
* be connected to only one right-side vertex, and hence must be so
* in the original graph as well (by construction). So we can
* discard this vertex pair from the graph, and any other edges
* that involved it (which will by construction be from other left
* vertices only), and the resulting smaller graph still has a
* unique perfect matching which means we can do the same thing
* again.
*
* In other words, given any bipartite graph with a unique perfect
* matching, we can find that matching by the following extremely
* simple algorithm:
*
* - Find a left-side vertex which is only connected to one
* right-side vertex.
* - Assign those vertices to one another, and therefore discard
* any other edges connecting to that right vertex.
* - Repeat until all vertices have been matched.
*
* This algorithm can be run in O(V+E) time (where V is the number
* of vertices and E is the number of edges in the graph), and the
* only way it can fail is if there is not a unique perfect
* matching (either because there is no matching at all, or because
* it isn't unique; but it can't distinguish those cases).
*
* Thus, the internal solver in this source file can be confident
* that if the tree/tent matching is uniquely determined by the
* tree and tent positions, it can find it using only this kind of
* obvious and simple operation: assign a tree to a tent if it
* cannot possibly belong to any other tent, and vice versa. If the
* solver were _only_ trying to determine the matching, even that
* `vice versa' wouldn't be required; but it can come in handy when
* not all the tents have been placed yet. I can therefore be
* reasonably confident that as long as my solver doesn't need to
* cope with grids that have a non-unique matching, it will also
* not need to do anything complicated like set analysis between
* trees and tents.
*/
/*
* 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
bool verbose = false;
#elif defined SOLVER_DIAGNOSTICS
#define verbose true
#endif
/*
* 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(TRICKY,Tricky,t)
#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 tents_diffnames[] = { DIFFLIST(TITLE) };
static char const tents_diffchars[] = DIFFLIST(ENCODE);
#define DIFFCONFIG DIFFLIST(CONFIG)
enum {
COL_BACKGROUND,
COL_GRID,
COL_GRASS,
COL_TREETRUNK,
COL_TREELEAF,
COL_TENT,
COL_ERROR,
COL_ERRTEXT,
COL_ERRTRUNK,
NCOLOURS
};
enum { BLANK, TREE, TENT, NONTENT, MAGIC };
struct game_params {
int w, h;
int diff;
};
struct numbers {
int refcount;
int *numbers;
};
struct game_state {
game_params p;
char *grid;
struct numbers *numbers;
bool completed, used_solve;
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
ret->w = ret->h = 8;
ret->diff = DIFF_EASY;
return ret;
}
static const struct game_params tents_presets[] = {
{8, 8, DIFF_EASY},
{8, 8, DIFF_TRICKY},
{10, 10, DIFF_EASY},
{10, 10, DIFF_TRICKY},
{15, 15, DIFF_EASY},
{15, 15, DIFF_TRICKY},
};
static bool game_fetch_preset(int i, char **name, game_params **params)
{
game_params *ret;
char str[80];
if (i < 0 || i >= lenof(tents_presets))
return false;
ret = snew(game_params);
*ret = tents_presets[i];
sprintf(str, "%dx%d %s", ret->w, ret->h, tents_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)
{
params->w = params->h = atoi(string);
while (*string && isdigit((unsigned char)*string)) string++;
if (*string == 'x') {
string++;
params->h = atoi(string);
while (*string && isdigit((unsigned char)*string)) string++;
}
if (*string == 'd') {
int i;
string++;
for (i = 0; i < DIFFCOUNT; i++)
if (*string == tents_diffchars[i])
params->diff = i;
if (*string) string++;
}
}
static char *encode_params(const game_params *params, bool full)
{
char buf[120];
sprintf(buf, "%dx%d", params->w, params->h);
if (full)
sprintf(buf + strlen(buf), "d%c",
tents_diffchars[params->diff]);
return dupstr(buf);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[80];
ret = snewn(4, 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 = "Difficulty";
ret[2].type = C_CHOICES;
ret[2].u.choices.choicenames = DIFFCONFIG;
ret[2].u.choices.selected = params->diff;
ret[3].name = NULL;
ret[3].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->diff = cfg[2].u.choices.selected;
return ret;
}
static const char *validate_params(const game_params *params, bool full)
{
/*
* Generating anything under 4x4 runs into trouble of one kind
* or another.
*/
if (params->w < 4 || params->h < 4)
return "Width and height must both be at least four";
return NULL;
}
/*
* Scratch space for solver.
*/
enum { N, U, L, R, D, MAXDIR }; /* link directions */
#define dx(d) ( ((d)==R) - ((d)==L) )
#define dy(d) ( ((d)==D) - ((d)==U) )
#define F(d) ( U + D - (d) )
struct solver_scratch {
char *links; /* mapping between trees and tents */
int *locs;
char *place, *mrows, *trows;
};
static struct solver_scratch *new_scratch(int w, int h)
{
struct solver_scratch *ret = snew(struct solver_scratch);
ret->links = snewn(w*h, char);
ret->locs = snewn(max(w, h), int);
ret->place = snewn(max(w, h), char);
ret->mrows = snewn(3 * max(w, h), char);
ret->trows = snewn(3 * max(w, h), char);
return ret;
}
static void free_scratch(struct solver_scratch *sc)
{
sfree(sc->trows);
sfree(sc->mrows);
sfree(sc->place);
sfree(sc->locs);
sfree(sc->links);
sfree(sc);
}
/*
* Solver. Returns 0 for impossibility, 1 for success, 2 for
* ambiguity or failure to converge.
*/
static int tents_solve(int w, int h, const char *grid, int *numbers,
char *soln, struct solver_scratch *sc, int diff)
{
int x, y, d, i, j;
char *mrow, *trow, *trow1, *trow2;
/*
* Set up solver data.
*/
memset(sc->links, N, w*h);
/*
* Set up solution array.
*/
memcpy(soln, grid, w*h);
/*
* Main solver loop.
*/
while (1) {
bool done_something = false;
/*
* Any tent which has only one unattached tree adjacent to
* it can be tied to that tree.
*/
for (y = 0; y < h; y++)
for (x = 0; x < w; x++)
if (soln[y*w+x] == TENT && !sc->links[y*w+x]) {
int linkd = 0;
for (d = 1; d < MAXDIR; d++) {
int x2 = x + dx(d), y2 = y + dy(d);
if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h &&
soln[y2*w+x2] == TREE &&
!sc->links[y2*w+x2]) {
if (linkd)
break; /* found more than one */
else
linkd = d;
}
}
if (d == MAXDIR && linkd == 0) {
#ifdef SOLVER_DIAGNOSTICS
if (verbose)
printf("tent at %d,%d cannot link to anything\n",
x, y);
#endif
return 0; /* no solution exists */
} else if (d == MAXDIR) {
int x2 = x + dx(linkd), y2 = y + dy(linkd);
#ifdef SOLVER_DIAGNOSTICS
if (verbose)
printf("tent at %d,%d can only link to tree at"
" %d,%d\n", x, y, x2, y2);
#endif
sc->links[y*w+x] = linkd;
sc->links[y2*w+x2] = F(linkd);
done_something = true;
}
}
if (done_something)
continue;
if (diff < 0)
break; /* don't do anything else! */
/*
* Mark a blank square as NONTENT if it is not orthogonally
* adjacent to any unmatched tree.
*/
for (y = 0; y < h; y++)
for (x = 0; x < w; x++)
if (soln[y*w+x] == BLANK) {
bool can_be_tent = false;
for (d = 1; d < MAXDIR; d++) {
int x2 = x + dx(d), y2 = y + dy(d);
if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h &&
soln[y2*w+x2] == TREE &&
!sc->links[y2*w+x2])
can_be_tent = true;
}
if (!can_be_tent) {
#ifdef SOLVER_DIAGNOSTICS
if (verbose)
printf("%d,%d cannot be a tent (no adjacent"
" unmatched tree)\n", x, y);
#endif
soln[y*w+x] = NONTENT;
done_something = true;
}
}
if (done_something)
continue;
/*
* Mark a blank square as NONTENT if it is (perhaps
* diagonally) adjacent to any other tent.
*/
for (y = 0; y < h; y++)
for (x = 0; x < w; x++)
if (soln[y*w+x] == BLANK) {
int dx, dy;
bool imposs = false;
for (dy = -1; dy <= +1; dy++)
for (dx = -1; dx <= +1; dx++)
if (dy || dx) {
int x2 = x + dx, y2 = y + dy;
if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h &&
soln[y2*w+x2] == TENT)
imposs = true;
}
if (imposs) {
#ifdef SOLVER_DIAGNOSTICS
if (verbose)
printf("%d,%d cannot be a tent (adjacent tent)\n",
x, y);
#endif
soln[y*w+x] = NONTENT;
done_something = true;
}
}
if (done_something)
continue;
/*
* Any tree which has exactly one {unattached tent, BLANK}
* adjacent to it must have its tent in that square.
*/
for (y = 0; y < h; y++)
for (x = 0; x < w; x++)
if (soln[y*w+x] == TREE && !sc->links[y*w+x]) {
int linkd = 0, linkd2 = 0, nd = 0;
for (d = 1; d < MAXDIR; d++) {
int x2 = x + dx(d), y2 = y + dy(d);
if (!(x2 >= 0 && x2 < w && y2 >= 0 && y2 < h))
continue;
if (soln[y2*w+x2] == BLANK ||
(soln[y2*w+x2] == TENT && !sc->links[y2*w+x2])) {
if (linkd)
linkd2 = d;
else
linkd = d;
nd++;
}
}
if (nd == 0) {
#ifdef SOLVER_DIAGNOSTICS
if (verbose)
printf("tree at %d,%d cannot link to anything\n",
x, y);
#endif
return 0; /* no solution exists */
} else if (nd == 1) {
int x2 = x + dx(linkd), y2 = y + dy(linkd);
#ifdef SOLVER_DIAGNOSTICS
if (verbose)
printf("tree at %d,%d can only link to tent at"
" %d,%d\n", x, y, x2, y2);
#endif
soln[y2*w+x2] = TENT;
sc->links[y*w+x] = linkd;
sc->links[y2*w+x2] = F(linkd);
done_something = true;
} else if (nd == 2 && (!dx(linkd) != !dx(linkd2)) &&
diff >= DIFF_TRICKY) {
/*
* If there are two possible places where
* this tree's tent can go, and they are
* diagonally separated rather than being
* on opposite sides of the tree, then the
* square (other than the tree square)
* which is adjacent to both of them must
* be a non-tent.
*/
int x2 = x + dx(linkd) + dx(linkd2);
int y2 = y + dy(linkd) + dy(linkd2);
assert(x2 >= 0 && x2 < w && y2 >= 0 && y2 < h);
if (soln[y2*w+x2] == BLANK) {
#ifdef SOLVER_DIAGNOSTICS
if (verbose)
printf("possible tent locations for tree at"
" %d,%d rule out tent at %d,%d\n",
x, y, x2, y2);
#endif
soln[y2*w+x2] = NONTENT;
done_something = true;
}
}
}
if (done_something)
continue;
/*
* If localised deductions about the trees and tents
* themselves haven't helped us, it's time to resort to the
* numbers round the grid edge. For each row and column, we
* go through all possible combinations of locations for
* the unplaced tents, rule out any which have adjacent
* tents, and spot any square which is given the same state
* by all remaining combinations.
*/
for (i = 0; i < w+h; i++) {
int start, step, len, start1, start2, n, k;
if (i < w) {
/*
* This is the number for a column.
*/
start = i;
step = w;
len = h;
if (i > 0)
start1 = start - 1;
else
start1 = -1;
if (i+1 < w)
start2 = start + 1;
else
start2 = -1;
} else {
/*
* This is the number for a row.
*/
start = (i-w)*w;
step = 1;
len = w;
if (i > w)
start1 = start - w;
else
start1 = -1;
if (i+1 < w+h)
start2 = start + w;
else
start2 = -1;
}
if (diff < DIFF_TRICKY) {
/*
* In Easy mode, we don't look at the effect of one
* row on the next (i.e. ruling out a square if all
* possibilities for an adjacent row place a tent
* next to it).
*/
start1 = start2 = -1;
}
k = numbers[i];
/*
* Count and store the locations of the free squares,
* and also count the number of tents already placed.
*/
n = 0;
for (j = 0; j < len; j++) {
if (soln[start+j*step] == TENT)
k--; /* one fewer tent to place */
else if (soln[start+j*step] == BLANK)
sc->locs[n++] = j;
}
if (n == 0)
continue; /* nothing left to do here */
/*
* Now we know we're placing k tents in n squares. Set
* up the first possibility.
*/
for (j = 0; j < n; j++)
sc->place[j] = (j < k ? TENT : NONTENT);
/*
* We're aiming to find squares in this row which are
* invariant over all valid possibilities. Thus, we
* maintain the current state of that invariance. We
* start everything off at MAGIC to indicate that it
* hasn't been set up yet.
*/
mrow = sc->mrows;
trow = sc->trows;
trow1 = sc->trows + len;
trow2 = sc->trows + 2*len;
memset(mrow, MAGIC, 3*len);
/*
* And iterate over all possibilities.
*/
while (1) {
int p;
bool valid;
/*
* See if this possibility is valid. The only way
* it can fail to be valid is if it contains two
* adjacent tents. (Other forms of invalidity, such
* as containing a tent adjacent to one already
* placed, will have been dealt with already by
* other parts of the solver.)
*/
valid = true;
for (j = 0; j+1 < n; j++)
if (sc->place[j] == TENT &&
sc->place[j+1] == TENT &&
sc->locs[j+1] == sc->locs[j]+1) {
valid = false;
break;
}
if (valid) {
/*
* Merge this valid combination into mrow.
*/
memset(trow, MAGIC, len);
memset(trow+len, BLANK, 2*len);
for (j = 0; j < n; j++) {
trow[sc->locs[j]] = sc->place[j];
if (sc->place[j] == TENT) {
int jj;
for (jj = sc->locs[j]-1; jj <= sc->locs[j]+1; jj++)
if (jj >= 0 && jj < len)
trow1[jj] = trow2[jj] = NONTENT;
}
}
for (j = 0; j < 3*len; j++) {
if (trow[j] == MAGIC)
continue;
if (mrow[j] == MAGIC || mrow[j] == trow[j]) {
/*
* Either this is the first valid
* placement we've found at all, or
* this square's contents are
* consistent with every previous valid
* combination.
*/
mrow[j] = trow[j];
} else {
/*
* This square's contents fail to match
* what they were in a different
* combination, so we cannot deduce
* anything about this square.
*/
mrow[j] = BLANK;
}
}
}
/*
* Find the next combination of k choices from n.
* We do this by finding the rightmost tent which
* can be moved one place right, doing so, and
* shunting all tents to the right of that as far
* left as they can go.
*/
p = 0;
for (j = n-1; j > 0; j--) {
if (sc->place[j] == TENT)
p++;
if (sc->place[j] == NONTENT && sc->place[j-1] == TENT) {
sc->place[j-1] = NONTENT;
sc->place[j] = TENT;
while (p--)
sc->place[++j] = TENT;
while (++j < n)
sc->place[j] = NONTENT;
break;
}
}
if (j <= 0)
break; /* we've finished */
}
/*
* It's just possible that _no_ placement was valid, in
* which case we have an internally inconsistent
* puzzle.
*/
if (mrow[sc->locs[0]] == MAGIC)
return 0; /* inconsistent */
/*
* Now go through mrow and see if there's anything
* we've deduced which wasn't already mentioned in soln.
*/
for (j = 0; j < len; j++) {
int whichrow;
for (whichrow = 0; whichrow < 3; whichrow++) {
char *mthis = mrow + whichrow * len;
int tstart = (whichrow == 0 ? start :
whichrow == 1 ? start1 : start2);
if (tstart >= 0 &&
mthis[j] != MAGIC && mthis[j] != BLANK &&
soln[tstart+j*step] == BLANK) {
int pos = tstart+j*step;
#ifdef SOLVER_DIAGNOSTICS
if (verbose)
printf("%s %d forces %s at %d,%d\n",
step==1 ? "row" : "column",
step==1 ? start/w : start,
mthis[j] == TENT ? "tent" : "non-tent",
pos % w, pos / w);
#endif
soln[pos] = mthis[j];
done_something = true;
}
}
}
}
if (done_something)
continue;
if (!done_something)
break;
}
/*
* The solver has nothing further it can do. Return 1 if both
* soln and sc->links are completely filled in, or 2 otherwise.
*/
for (y = 0; y < h; y++)
for (x = 0; x < w; x++) {
if (soln[y*w+x] == BLANK)
return 2;
if (soln[y*w+x] != NONTENT && sc->links[y*w+x] == 0)
return 2;
}
return 1;
}
static char *new_game_desc(const game_params *params_in, random_state *rs,
char **aux, bool interactive)
{
game_params params_copy = *params_in; /* structure copy */
game_params *params = ¶ms_copy;
int w = params->w, h = params->h;
int ntrees = w * h / 5;
char *grid = snewn(w*h, char);
char *puzzle = snewn(w*h, char);
int *numbers = snewn(w+h, int);
char *soln = snewn(w*h, char);
int *order = snewn(w*h, int);
int *treemap = snewn(w*h, int);
int maxedges = ntrees*4 + w*h;
int *adjdata = snewn(maxedges, int);
int **adjlists = snewn(ntrees, int *);
int *adjsizes = snewn(ntrees, int);
int *outr = snewn(4*ntrees, int);
struct solver_scratch *sc = new_scratch(w, h);
char *ret, *p;
int i, j, nl, nr;
int *adjptr;
/*
* Since this puzzle has many global deductions and doesn't
* permit limited clue sets, generating grids for this puzzle
* is hard enough that I see no better option than to simply
* generate a solution and see if it's unique and has the
* required difficulty. This turns out to be computationally
* plausible as well.
*
* We chose our tree count (hence also tent count) by dividing
* the total grid area by five above. Why five? Well, w*h/4 is
* the maximum number of tents you can _possibly_ fit into the
* grid without violating the separation criterion, and to
* achieve that you are constrained to a very small set of
* possible layouts (the obvious one with a tent at every
* (even,even) coordinate, and trivial variations thereon). So
* if we reduce the tent count a bit more, we enable more
* random-looking placement; 5 turns out to be a plausible
* figure which yields sensible puzzles. Increasing the tent
* count would give puzzles whose solutions were too regimented
* and could be solved by the use of that knowledge (and would
* also take longer to find a viable placement); decreasing it
* would make the grids emptier and more boring.
*
* Actually generating a grid is a matter of first placing the
* tents, and then placing the trees by the use of matching.c
* (finding a distinct square adjacent to every tent). We do it
* this way round because otherwise satisfying the tent
* separation condition would become onerous: most randomly
* chosen tent layouts do not satisfy this condition, so we'd
* have gone to a lot of work before finding that a candidate
* layout was unusable. Instead, we place the tents first and
* ensure they meet the separation criterion _before_ doing
* lots of computation; this works much better.
*
* This generation strategy can fail at many points, including
* as early as tent placement (if you get a bad random order in
* which to greedily try the grid squares, you won't even
* manage to find enough mutually non-adjacent squares to put
* the tents in). Then it can fail if matching.c doesn't manage
* to find a good enough matching (i.e. the tent placements don't
* admit any adequate tree placements); and finally it can fail
* if the solver finds that the problem has the wrong
* difficulty (including being actually non-unique). All of
* these, however, are insufficiently frequent to cause
* trouble.
*/
if (params->diff > DIFF_EASY && params->w <= 4 && params->h <= 4)
params->diff = DIFF_EASY; /* downgrade to prevent tight loop */
while (1) {
/*
* Make a list of grid squares which we'll permute as we pick
* the tent locations.
*
* We'll also need to index all the potential tree squares,
* i.e. the ones adjacent to the tents.
*/
for (i = 0; i < w*h; i++) {
order[i] = i;
treemap[i] = -1;
}
/*
* Place tents at random without making any two adjacent.
*/
memset(grid, BLANK, w*h);
j = ntrees;
nr = 0;
/* Loop end condition: either j==0 (we've placed all the
* tents), or the number of grid squares we have yet to try
* is too few to fit the remaining tents into. */
for (i = 0; j > 0 && i+j <= w*h; i++) {
int which, x, y, d, tmp;
int dy, dx;
bool ok = true;