-
Notifications
You must be signed in to change notification settings - Fork 1
/
ms_solve.c
1306 lines (1181 loc) · 38.7 KB
/
ms_solve.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
/* Minesweeper Consistency Problem solver.
Written by Chen Guo, UCLA CS 261A project spring 2011.
*/
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <pthread.h>
#include <unistd.h>
/* Defines. */
#define INBUF_SIZ 1024
#define TILE_ZERO 1000000
#define TILE_MAP(val) (val - '0') // Numbered tiles are mapped to
#define TILE_UNMAP(val) (val + '0') // 1000000 - 1000008
#define UNKNOWN 9
#define MINE_ON 10
#define MINE_OFF -10
#define UNKNOWN_CHAR '?'
#define MINE_ON_CHAR '*'
#define MINE_OFF_CHAR '-'
#define LOCK {pthread_mutex_lock (thr_lock);}
#define UNLOCK {pthread_mutex_unlock (thr_lock);}
/*****************************************************************************
*
* Structures
*
****************************************************************************/
/* Index in 2D grid. */
struct ind
{
int row;
int col;
};
/* Buffers used for search. */
struct buffers
{
int *buf; // Array for grid.
int **grid; // 2D array for grid.
struct ind *ind; // Array of indices to unknowns.
};
/* Individual thread data. */
struct search
{
pthread_t thread; // Thread object.
bool avail; // Available flag.
struct buffers bufs; // Thread individual buffers used for search.
};
/* solve_tree () arguments for threading. */
struct thr_args
{
int thread_num; // Number of thread being used.
int unknown_num; // Number of unknown being inspected.
int mine_count; // Number of mines turned on thus far.
};
/* Struct used for sorting unknown tiles. */
struct sort_tile
{
struct ind index; // Index of unknown tile.
int number_tiles; // Number of surrounding tiles with numbers.
};
/*****************************************************************************
*
* Globals
*
****************************************************************************/
/* Globals. */
static int nrows;
static int ncols;
static int ntiles;
static int total_unknowns; // Total possible mine positions.
static int goal_states = 0; // Total goal states found, with constraints.
/* Argument settings. */
static bool force = false; // Force unknown states during search.
static bool preresolve = false; // Preresolve uknowns before search.
static bool single = true; // Find all solutions (opposed to just one)
static bool sort = false; // Sort unknown order.
static int mine_target = -1; // Number of desired mines in solution.
enum { PRINT_NONE, PRINT_MIN, PRINT_BASIC, PRINT_ALL, PRINT_DEBUG };
static int print = PRINT_BASIC; // Print boards.
static int guess = false;
static int diag = false;
/* For thread control */
static int max_threads = 1; // Threads to use.
static int avail_threads = 1; // Available threads.
static struct search *thr_data; // Array of search data, for threads.
static pthread_mutex_t *thr_lock; // Thread control mutex.
static pthread_cond_t *thr_cond; // Thread control cond var.
static __thread int thread_num; // Thread number.
/* Function prototypes. */
/* Preprocess functions. */
static void preprocess_grid ();
/* Grid solver functions. */
static void * solve_tree_thr (void *);
static int solve_tree (int, int, struct buffers);
static int solve_subtree (int, int, struct buffers, bool);
static bool consistency_check (struct ind, int **, int, bool);
static int find_unknowns (int **, struct ind *);
static void clear_unknowns (int, struct ind *, int **);
static inline int force_on (int);
static inline int force_off (int);
static inline bool is_mine (int);
static inline int mine_src (int);
/* Thread control functions. */
static void thread_alloc ();
static void thread_struct_alloc ();
static int thread_find ();
static void thread_free ();
static void thread_copy (int, int);
/* Misc functions. */
static void diag_print (struct ind *, int **);
static void board_print (int **);
static void parse_input (char *);
static void help ();
int main (int argc, char **argv)
{
// Parse arguments.
char c;
while ((c = getopt (argc, argv, "adfhm:p:rst:")) != -1)
{
switch (c)
{
// Find all solutions.
case 'a':
single = false;
break;
// Diagnostic: print state of blank and sum of surrounding tiles.
// Note: don't put this in -h message.
case 'd':
diag = true;
break;
// Force unknown state during search.
case 'f':
force = true;
break;
// Guess the state of the next mine. Only in effect if a target
// number of mines is set.
case 'g':
guess = true;
break;
// Help. Does not return.
case 'h':
help ();
// Target number of mines.
case 'm':
mine_target = atoi (optarg);
break;
// Print.
case 'p':
print = atoi (optarg);
break;
// Pre-resolve unknowns.
case 'r':
preresolve = true;
break;
// Sort unknowns by number of surrounding tiles.
case 's':
sort = true;
break;
// Threads tp use.
case 't':
max_threads = atoi(optarg);
// Current thread is a thread, so max-1 are available.
avail_threads = max_threads;
break;
}
}
int num_goals = 0;
char *file = argv[optind];
if (print >= PRINT_BASIC)
printf ("Processing file %s\n", file);
// Allocate structures for threads.
thread_alloc ();
// Parse the input file. The buffers for each thread structure
// is allocated here.
parse_input (file);
// Begin processing file. Start timer.
struct timeval timer_start, timer_pre, timer_end;
double total_time, pre_time, search_time;
if (print >= PRINT_MIN)
gettimeofday (&timer_start, NULL);
// Preprocess the grid to prepare for search. Assigns global value
// TOTAL_UNKNOWNS.
preprocess_grid ();
if (print >= PRINT_MIN)
gettimeofday (&timer_pre, NULL);
// NOTE: in defines, mapping tile values to 1000000 - 1000008 assumes that
// there will NEVER be more than 1 million unknowns.
if (total_unknowns >= 1000000)
fprintf (stderr, "Too many unknowns, search not performed.\n");
else if (total_unknowns > 0)
{
// Attempt to find a solution, or multiple solutions.
// Spin off search thread in thread 0, and wait.
struct thr_args args = {0, 0, 0};
pthread_t thread;
LOCK;
pthread_create (&thread, NULL, solve_tree_thr, &args);
pthread_detach (thread);
pthread_cond_wait (thr_cond, thr_lock);
UNLOCK;
}
else
{
// Trivially a goal state.
if (print >= PRINT_ALL)
board_print (thr_data[0].bufs.grid);
goal_states++;
}
if (print >= PRINT_BASIC)
printf ("Number of goal states: %d\n", goal_states);
// Find elapsed time in us.
if (print >= PRINT_MIN)
{
gettimeofday (&timer_end, NULL);
pre_time = (timer_pre.tv_sec * 1000.0) + (timer_pre.tv_usec/1000.0)
- (timer_start.tv_sec * 1000.0) - (timer_start.tv_usec / 1000.0);
printf ("Preprocess time: %f ms\n", pre_time);
search_time = (timer_end.tv_sec * 1000.0) + (timer_end.tv_usec/1000.0)
- (timer_pre.tv_sec * 1000.0) - (timer_pre.tv_usec / 1000.0);
printf ("Search time: %f ms\n", search_time);
total_time = (timer_end.tv_sec * 1000.0) + (timer_end.tv_usec/1000.0)
- (timer_start.tv_sec * 1000.0) - (timer_start.tv_usec / 1000.0);
printf ("Elapsed time: %f ms\n", total_time);
}
// Free thread resources.
//thread_free ();
}
/*****************************************************************************
*
* Preprocess functions.
*
****************************************************************************/
/* Given a tile, if it is a numbered tile, count the mines and unknowns around
it. If the count matches the tile number, then all unknowns around must be
mines. Conversely, if the count matches the mine number, then all unknowns
must be off.
SOURCE denotes the index of the unknown tile that this resolution stems
from. */
static int resolve_tile (int row, int col, int **grid, int source, bool rec)
{
struct ind ind[8];
int pos[8];
int unknowns = 0;
int mines = 0;
int resolved = 0;
int i, j;
int tile_num = grid[row][col];
if (tile_num < 0 || tile_num > 8)
return 0;
int position = 0;
for (i = -1; i < 2; i++)
for (j = -1; j < 2; j++)
{
// Upon finding an unknown, record it's position.
if (grid[row+i][col+j] == UNKNOWN)
{
ind[unknowns].row = row + i;
ind[unknowns].col = col + j;
pos[unknowns++] = position;
}
else if (is_mine (grid[row+i][col+j]))
mines++;
position++;
}
// If TILE_NUM matches the sum of mines and unkowns, all the unknowns are
// mines. If TILE_NUM matches the mines, then all unknowns are off. Set
// the unknowns accordingly, and check the tiles around the former
// unknowns.
bool turn_on;
if (tile_num == mines + unknowns)
{
turn_on = true;
int k;
for (k = 0; k < unknowns; k++)
{
if (print >= PRINT_DEBUG)
fprintf (stderr, "[%d][%d] forced on\n", ind[k].row, ind[k].col);
grid[ind[k].row][ind[k].col] = force_on (source);
}
}
else if (tile_num == mines)
{
turn_on = false;
int k;
for (k = 0; k < unknowns; k++)
{
if (print >= PRINT_DEBUG)
fprintf (stderr, "[%d][%d] forced off\n", ind[k].row, ind[k].col);
grid[ind[k].row][ind[k].col] = force_off (source);
}
}
else
return 0;
resolved = unknowns;
return resolved;
// Check for recursive mode.
// Source position: 0 1 2
// 3 4 5
// 6 7 8
// Recursive calls occur around a blank that was around the original tile.
// Based on the position of the blank, only some tiles need to be examined.
// We'll map it as such:
// Position 0: inspect L, UL, U
// Position 1: U
// Position 2: U, UR, R
// Position 3: L
// Position 4: impossible
// Position 5: R
// Position 6: L, BL, B
// Position 7: B
// Position 8: B, BR, R
// TODO: control direction of frontier in recursion, for effcieny (i.e. don't
// recheck what your parent just checked. */
if (rec)
{
// For each unknown that was resolved, check it's neighbors.
int k;
bool checked[16];
// 0 1 2 3 4
// 5 0 1 2 6
// 7 3 5 8
// 9 6 7 8 10
// 11 12 13 14 15
for (k = 0; k < unknowns; k++)
{
row = ind[k].row;
col = ind[k].col;
switch (pos[k])
{
case 0: // BL L UL U UR
if (!checked[7])
{
resolved += resolve_tile (row+1, col-1, grid, source, rec);
checked[7] = true;
}
if (!checked[5])
{
resolved += resolve_tile (row, col-1, grid, source, rec);
checked[5] = true;
}
if (!checked[0])
{
resolved += resolve_tile (row-1, col-1, grid, source, rec);
checked[0] = true;
}
if (!checked[1])
{
resolved += resolve_tile (row-1, col, grid, source, rec);
checked[1] = true;
}
if (!checked[2])
{
resolved += resolve_tile (row-1, col+1, grid, source, rec);
checked[2] = true;
}
break;
case 1: // UL U UR
if (!checked[1])
{
resolved += resolve_tile (row-1, col-1, grid, source, rec);
checked[1] = true;
}
if (!checked[2])
{
resolved += resolve_tile (row-1, col, grid, source, rec);
checked[2] = true;
}
if (!checked[3])
{
resolved += resolve_tile (row-1, col+1, grid, source, rec);
checked[3] = true;
}
break;
case 2: // UL U UR R BR
if (!checked[2])
{
resolved += resolve_tile (row-1, col-1, grid, source, rec);
checked[2] = true;
}
if (!checked[3])
{
resolved += resolve_tile (row-1, col, grid, source, rec);
checked[3] = true;
}
if (!checked[4])
{
resolved += resolve_tile (row-1, col+1, grid, source, rec);
checked[4] = true;
}
if (!checked[6])
{
resolved += resolve_tile (row, col+1, grid, source, rec);
checked[6] = true;
}
if (!checked[8])
{
resolved += resolve_tile (row+1, col+1, grid, source, rec);
checked[8];
}
break;
case 3:
if (!checked[5])
{
resolved += resolve_tile (row-1, col-1, grid, source, rec);
checked[5] = true;
}
if (!checked[7])
{
resolved += resolve_tile (row, col-1, grid, source, rec);
checked[7] = true;
}
if (!checked[9])
{
resolved += resolve_tile (row+1, col-1, grid, source, rec);
checked[9] = true;
}
break;
case 5:
if (!checked[6])
{
resolved += resolve_tile (row-1, col+1, grid, source, rec);
checked[6] = true;
}
if (!checked[8])
{
resolved += resolve_tile (row, col+1, grid, source, rec);
checked[8] = true;
}
if (!checked[10])
{
resolved += resolve_tile (row+1, col+1, grid, source, rec);
checked[10] = true;
}
break;
case 6:
if (!checked[7])
{
resolved += resolve_tile (row-1, col-1, grid, source, rec);
checked[7] = true;
}
if (!checked[9])
{
resolved += resolve_tile (row, col-1, grid, source, rec);
checked[9] = true;
}
if (!checked[11])
{
resolved += resolve_tile (row+1, col-1, grid, source, rec);
checked[11] = true;
}
if (!checked[12])
{
resolved += resolve_tile (row+1, col, grid, source, rec);
checked[12] = true;
}
if (!checked[13])
{
resolved += resolve_tile (row+1, col+1, grid, source, rec);
checked[13];
}
break;
case 7:
if (!checked[12])
{
resolved += resolve_tile (row+1, col-1, grid, source, rec);
checked[12] = true;
}
if (!checked[13])
{
resolved += resolve_tile (row+1, col, grid, source, rec);
checked[13] = true;
}
if (!checked[14])
{
resolved += resolve_tile (row+1, col+1, grid, source, rec);
checked[14] = true;
}
break;
case 8:
if (!checked[13])
{
resolved += resolve_tile (row+1, col-1, grid, source, rec);
checked[13] = true;
}
if (!checked[14])
{
resolved += resolve_tile (row+1, col, grid, source, rec);
checked[14] = true;
}
if (!checked[15])
{
resolved += resolve_tile (row+1, col+1, grid, source, rec);
checked[15] = true;
}
if (!checked[10])
{
resolved += resolve_tile (row, col+1, grid, source, rec);
checked[10] = true;
}
if (!checked[8])
{
resolved += resolve_tile (row-1, col+1, grid, source, rec);
checked[8];
}
break;
}
}
}
return resolved;
}
/* This function attempts to resolve some unknown tiles before we start the
search. Essentially, this will reduce the depth of the search tree. */
static int preresolve_grid ()
{
int i, j;
int resolved = 0;
int **grid = thr_data[0].bufs.grid;
for (i = 1; i < nrows - 1; i++)
for (j = 1; j < ncols - 1; j++)
resolved += resolve_tile (i, j, grid, -1, false);
return resolved;
}
/* Find the unknowns in the grid, and establish the indices. */
static int find_unknowns (int **grid, struct ind *ind)
{
int i, j, n = 0;
for (i = 1; i < nrows - 1; i++)
for (j = 1; j < ncols - 1; j++)
{
if (grid[i][j] == UNKNOWN)
{
ind[n].row = i;
ind[n++].col = j;
//rintf (stderr, "UNKNOWN at [%d][%d]\n", i, j);
}
}
ind[n].row = -1;
ind[n].col = -1;
return n;
}
/* Comparator function to pass to qsort (), when sorting unknown tiles. */
int comp_tiles (const void *arg1, const void *arg2)
{
struct sort_tile *a = (struct sort_tile *) arg1;
struct sort_tile *b = (struct sort_tile *) arg2;
// Compare the NUMBER_TILES field.
if (a->number_tiles > b->number_tiles)
return -1;
else if (a->number_tiles < b->number_tiles)
return 1;
else
return 0;
}
/* Sort the unknown tiles by constraint order. The unknowns with more
surrounding numbered tiles will come first, and thus be searched first. */
static void sort_unknowns (int **grid, struct ind *ind)
{
struct sort_tile *unknown_tiles =
(struct sort_tile *) malloc (total_unknowns * sizeof *unknown_tiles);
// Count the number of mines around each unknown tile.
int i;
for (i = 0; i < total_unknowns; i++)
{
unknown_tiles[i].index = ind[i];
int number_tiles = 0;
int row = ind[i].row;
int col = ind[i].col;
int j, k;
for (j = -1; j < 2; j++)
for (k = -1; k < 2; k++)
{
int tile_num = grid[row+j][col+k];
if (0 <= tile_num && tile_num <= 8)
number_tiles++;
}
unknown_tiles[i].number_tiles = number_tiles;
}
// Sort the unknown tiles.
qsort (unknown_tiles, total_unknowns,
sizeof (struct sort_tile), comp_tiles);
// Copy sorted results back into IND.
for (i = 0; i < total_unknowns; i++)
ind[i] = unknown_tiles[i].index;
}
/* Count the number of current existing mines on the field,
and adjusts the MINE_TARGET field accordingly.
This function also calls a few functions that scan through the unknown
tiles, and these functions can be combined, but that is neglected because
the small time spend iterating through the grid is negligible compared to
the exponential time needed to solve the consistency problem. */
static void preprocess_grid ()
{
int **grid = thr_data[0].bufs.grid;
struct ind *ind = thr_data[0].bufs.ind;
// Preprocess grid, if specified.
int resolved = 0;
if (preresolve)
resolved = preresolve_grid ();
if (print >= PRINT_MIN)
printf ("Pre-resolved unknowns: %d\n", resolved);
if (print >= PRINT_BASIC && preresolve)
board_print (thr_data[0].bufs.grid);
// If no MINE_TARGET was set, there is no need to adjust it.
if (mine_target > -1)
{
int i, j;
for (i = 1; i < nrows - 1; i++)
for (j = 1; j < ncols - 1; j++)
if (is_mine (grid[i][j]))
mine_target--;
}
// Find all the unknowns.
total_unknowns = find_unknowns (grid, ind);
// Sort the unknowns (by surrounding tiles) if specified.
if (sort)
sort_unknowns (grid, ind);
}
/*****************************************************************************
*
* Solver functions.
*
****************************************************************************/
/* Threaded function call for solve_tree. */
static void * solve_tree_thr (void *data)
{
struct thr_args *args = (struct thr_args *) data;
thread_num = args->thread_num;
int tmp = args->thread_num;
struct buffers bufs = thr_data[thread_num].bufs;
int num_goals = solve_tree (args->unknown_num, args->mine_count, bufs);
// Critical section.
// 1) Update goals found.
// 2) Mark thread as available.
// 3) Check for end of execution.
bool signal = false;
LOCK;
goal_states += num_goals;
thr_data[tmp].avail = true;
avail_threads++;
if (avail_threads == max_threads || (single && num_goals))
pthread_cond_signal (thr_cond);
UNLOCK;
return NULL;
}
/* Solve the game board with brute force algorithm. The algorithm takes a trial
and error approach, placing one mine at a time. Backtracking and pruning of
the search tree are employed when an inconsistent game board is encountered.
This algorithm is based on Neville Mehta's, ported from Lisp to C++ by
Meredith Kadlac, but is much more optimized and performs more than 20x
faster. */
static int solve_tree (int unknown_num, int mine_count, struct buffers bufs)
{
int num_goals = 0;
int row = bufs.ind[unknown_num].row;
int col = bufs.ind[unknown_num].col;
if (mine_src (bufs.grid[row][col]) >= 0)
{
// Unknown was pre-assigned. Just move on to next unknown if consistent.
if (!consistency_check (bufs.ind[unknown_num], bufs.grid, unknown_num, false))
return 0;
if (is_mine (bufs.grid[row][col]))
mine_count++;
if (unknown_num == total_unknowns - 1
&& (mine_target == -1 || mine_count == mine_target))
{
num_goals++;
if (diag)
diag_print (bufs.ind, bufs.grid);
if (print >= PRINT_ALL)
board_print (bufs.grid);
}
else if (unknown_num < total_unknowns - 1)
num_goals = solve_tree (unknown_num+1, mine_count, bufs);
}
else if (mine_count == mine_target)
{
// All mines are used up, just check the MINE_OFF subtree. Do not thread.
bufs.grid[row][col] = force_off (unknown_num);
num_goals = solve_subtree (unknown_num, mine_count, bufs, false);
}
else if ((mine_target - mine_count) == (total_unknowns - unknown_num - 1))
{
// To be a solution, all remaining mines must be on. Just check the
// MINE_ON subtree. Do not thread.
bufs.grid[row][col] = force_on (unknown_num);
num_goals = solve_subtree (unknown_num, mine_count + 1, bufs, false);
}
else if (mine_target == -1 || mine_count < mine_target)
{
// Check both subtrees. For the first subtree, instruct it to spin off a
// thread if a thread is available.
// Determine which subtree to check first.
bool mine_on = false;
// Check the first subtree. Thread if possible.
if (mine_on)
{
if (print >= PRINT_DEBUG)
fprintf (stderr, "[%d][%d] on\n", row, col);
bufs.grid[row][col] = force_on (unknown_num);
mine_count++;
}
else
{
if (print >= PRINT_DEBUG)
fprintf (stderr, "[%d][%d] off\n", row, col);
bufs.grid[row][col] = force_off (unknown_num);
}
num_goals = solve_subtree (unknown_num, mine_count, bufs, true);
// If only a single solution is desired, and it's been found,
// then we're done.
if (single && num_goals)
return num_goals;
// Check the other subtree. Do not thread.
mine_on = !mine_on;
if (mine_on)
{
if (print >= PRINT_DEBUG)
fprintf (stderr, "[%d][%d] on\n", row, col);
bufs.grid[row][col] = force_on (unknown_num);
mine_count++;
}
else
{
if (print >= PRINT_DEBUG)
fprintf (stderr, "[%d][%d] off\n", row, col);
bufs.grid[row][col] = force_off (unknown_num);
}
clear_unknowns (unknown_num, bufs.ind, bufs.grid);
num_goals += solve_subtree (unknown_num, mine_count, bufs, false);
}
return num_goals;
}
/* */
static int solve_subtree (int unknown_num, int mine_count, struct buffers bufs,
bool create_thread)
{
int num_goals = 0;
int row = bufs.ind[unknown_num].row;
int col = bufs.ind[unknown_num].col;
bool consis = consistency_check (bufs.ind[unknown_num], bufs.grid,
unknown_num, true);
if (consis)
{
// The mine state is valid. Check for subtrees, or if this branch of
// the search tree is exhausted.
if (unknown_num < total_unknowns - 1
&& (mine_target == -1 || mine_count <= mine_target))
{
// A subtree exists:
// 1) Not all unknowns are assigned.
// 2) If MINE_TARGET is specified, it has not been exceeded.
// Check if we should create a new thread.
if (create_thread
&& (mine_target == -1 || mine_count < mine_target)
&& (total_unknowns - unknown_num > 10))
{
LOCK;
if (avail_threads <= 0)
{
UNLOCK;
create_thread = false;
}
else
{
// Find a thread and claim it.
int new_thr = thread_find (0);
thr_data[new_thr].avail = false;
avail_threads--;
UNLOCK;
// Copy buffers into new thread.
thread_copy (new_thr, thread_num);
struct thr_args *args =
(struct thr_args *) malloc (sizeof *args);
args->thread_num = new_thr;
args->unknown_num = unknown_num + 1;
args->mine_count = mine_count;
pthread_create (&thr_data[new_thr].thread, NULL,
solve_tree_thr, args);
pthread_detach (thr_data[new_thr].thread);
}
}
else
{
create_thread = false;
}
if (!create_thread)
{
//fprintf (stderr, "Rec call\n");
num_goals = solve_tree (unknown_num + 1, mine_count, bufs);
}
}
else if (unknown_num == total_unknowns - 1
&& (mine_target == -1 || mine_count == mine_target))
{
// Solution has been found:
// 1) All unknowns have been assigned a valid state.
// 2) MINE_TARGET, if specified, has been matched.
num_goals++;
if (diag)
diag_print (bufs.ind, bufs.grid);
if (print >= PRINT_ALL)
board_print (bufs.grid);
}
else
{
// The remaining case is that all unknown tiles have been assigned,
// and MINE_TARGET was specified but not reached. Here, there is
// nothing to be done.
}
}
else
{
//fprintf (stderr, "[%d][%d] consis failed\n", row, col);
//board_print (bufs.grid);
}
return num_goals;
}
/*
This function only checks the tiles around the mine that was most recently
turned on/off, since the validity of other tiles would not be affected.
Given:
N: number on tile.
M: mines surrounding tile.
Q: unknown tiles surrounding tile.
A tile is consistent if M <= N <= M + Q
*/
static bool consistency_check (struct ind ind, int **grid, int unknown_num,
bool check_force)
{
int row = ind.row;
int col = ind.col;
int i;
int j;
//fprintf (stderr, "Checking [%d][%d]\n", row, col);
for (i = -1; i < 2; i++)
for (j = -1; j < 2; j++)
{
// For each numbered tile around mine:
int tile_num = grid[row+i][col+j];
if (0 <= tile_num && tile_num <= 8)
{
int local_mines = 0;
int local_unknowns = 0;
int k;
int l;
// Count number of mines and unknowns around tile.
for (k = -1; k < 2; k++)
for (l = -1; l < 2; l++)
{
if (is_mine (grid[row+i+k][col+j+l]))
local_mines++;
else if (grid[row+i+k][col+j+l] == UNKNOWN)
local_unknowns++;
}
//fprintf (stderr, " grid[%d][%d]: %d: mines %d unknowns %d\n",
// row + i, col + j, tile_num, local_mines, local_unknowns);
// Perform the consistency check.
if (tile_num < local_mines
|| tile_num > local_mines + local_unknowns)
{
//fprintf (stderr, "[%d+%d][%d+%d] inconsis: tile %d mines %d unknowns %d\n",
// row, i, col, j, tile_num, local_mines, local_unknowns);
//board_print (grid);
return false;
}
// If specified, see if we can force neighboring mine states.
//if (force && (i == 1 || (i == 0 && j == 1)))
// {
// resolve_tile (row+i, col+j, grid, unknown_num, false);
// }
}
}
if (force && check_force)
{
resolve_tile (row, col + 1, grid, unknown_num, false);
for (j = -1; j < 2; j++)
resolve_tile (row + 1, col + j, grid, unknown_num, false);
}
return true;
}
/* Set mines to UNKNOWN from the one after index I. However, if a mine is
forced by an unknown indexed earlier than I, don't touch it. */
static inline void clear_unknowns (int i, struct ind *ind, int **grid)
{
int init = i++;
if (!force)
{
while (i < total_unknowns)
grid[ind[i].row][ind[i++].col] = UNKNOWN;
}
else
{
while (i < total_unknowns)
{
int src = mine_src (grid[ind[i].row][ind[i].col]);
if (src >= init)
{
grid[ind[i].row][ind[i].col] = UNKNOWN;
}
i++;
}
}
}
/* When an unknown is forced on/off, use this function to set the value.
Later, we can determine which unknown forced this unknown to turn on/off. */