This repository has been archived by the owner on Dec 12, 2020. It is now read-only.
forked from microsoft/nurikabe
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnurikabe.cpp
1414 lines (1089 loc) · 44.2 KB
/
nurikabe.cpp
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Nurikabe Solver by Stephan T. Lavavej
// https://en.wikipedia.org/wiki/Nurikabe_(puzzle)
// clang++ -Os -std=c++17 -o nurikabe nurikabe.cpp && nurikabe && grumphunt-prequel.html
#include <stddef.h>
#include <stdlib.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <exception>
#include <fstream>
#include <iostream>
#include <iterator>
#include <map>
#include <memory>
#include <ostream>
#include <queue>
#include <random>
#include <ratio>
#include <regex>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;
using namespace std::chrono;
class Grid {
public:
Grid(int width, int height, const string& s);
enum SitRep {
CONTRADICTION_FOUND,
SOLUTION_FOUND,
KEEP_GOING,
CANNOT_PROCEED
};
SitRep solve(bool verbose = true, bool guessing = true);
int known() const;
void write(ostream& os, steady_clock::time_point start, steady_clock::time_point finish) const;
private:
// The states that a cell can be in. Numbered cells are positive,
// which is why this has an explicitly specified underlying type.
enum State : int {
UNKNOWN = -3,
WHITE = -2,
BLACK = -1
};
// Each region is black, white, or numbered. This allows us to
// remember when white cells are connected to numbered cells,
// as the whole region is marked as numbered.
// Each region keeps track of the coordinates that it occupies.
// Each region also keeps track of the unknown cells that it's surrounded by.
class Region {
public:
Region(const State state, const int x, const int y, const set<pair<int, int>>& unknowns)
: m_state(state), m_coords(), m_unknowns(unknowns) {
if (state == UNKNOWN) {
throw logic_error("LOGIC ERROR: Grid::Region::Region() - state must be known!");
}
m_coords.insert(make_pair(x, y));
}
bool white() const {
return m_state == WHITE;
}
bool black() const {
return m_state == BLACK;
}
bool numbered() const {
return m_state > 0;
}
int number() const {
if (!numbered()) {
throw logic_error(
"LOGIC ERROR: Grid::Region::number() - This region is not numbered!");
}
return m_state;
}
set<pair<int, int>>::const_iterator begin() const {
return m_coords.begin();
}
set<pair<int, int>>::const_iterator end() const {
return m_coords.end();
}
int size() const {
return static_cast<int>(m_coords.size());
}
bool contains(const int x, const int y) const {
return m_coords.find(make_pair(x, y)) != m_coords.end();
}
template <typename InIt> void insert(InIt first, InIt last) {
m_coords.insert(first, last);
}
set<pair<int, int>>::const_iterator unk_begin() const {
return m_unknowns.begin();
}
set<pair<int, int>>::const_iterator unk_end() const {
return m_unknowns.end();
}
int unk_size() const {
return static_cast<int>(m_unknowns.size());
}
template <typename InIt> void unk_insert(InIt first, InIt last) {
m_unknowns.insert(first, last);
}
void unk_erase(const int x, const int y) {
m_unknowns.erase(make_pair(x, y));
}
private:
State m_state;
set<pair<int, int>> m_coords;
set<pair<int, int>> m_unknowns;
};
typedef map<shared_ptr<Region>, set<pair<int, int>>> cache_map_t;
bool analyze_complete_islands(bool verbose);
bool analyze_single_liberties(bool verbose);
bool analyze_dual_liberties(bool verbose);
bool analyze_unreachable_cells(bool verbose);
bool analyze_potential_pools(bool verbose);
bool analyze_confinement(bool verbose, cache_map_t& cache);
vector<pair<int, int>> guessing_order();
bool analyze_hypotheticals(bool verbose);
// We use an upper-left origin.
// This is convenient during construction and printing.
// It's irrelevant during analysis.
bool valid(int x, int y) const;
State& cell(int x, int y);
const State& cell(int x, int y) const;
shared_ptr<Region>& region(int x, int y);
const shared_ptr<Region>& region(int x, int y) const;
void print(const string& s, const set<pair<int, int>>& updated = {},
int failed_guesses = 0, const set<pair<int, int>>& failed_coords = {});
bool process(bool verbose, const set<pair<int, int>>& mark_as_black,
const set<pair<int, int>>& mark_as_white, const string& s,
int failed_guesses = 0, const set<pair<int, int>>& failed_coords = {});
template <typename F> void for_valid_neighbors(int x, int y, F f) const;
void insert_valid_neighbors(set<pair<int, int>>& s, int x, int y) const;
void insert_valid_unknown_neighbors(set<pair<int, int>>& s, int x, int y) const;
void add_region(int x, int y);
void mark(State s, int x, int y);
void fuse_regions(shared_ptr<Region> r1, shared_ptr<Region> r2);
bool impossibly_big_white_region(int n) const;
bool unreachable(int x_root, int y_root,
set<pair<int, int>> discovered = {}) const;
bool confined(const shared_ptr<Region>& r, cache_map_t& cache,
const set<pair<int, int>>& verboten = {}) const;
bool detect_contradictions(bool verbose, cache_map_t& cache);
int m_width; // x is valid within [0, m_width).
int m_height; // y is valid within [0, m_height).
int m_total_black; // The total number of black cells that will be in the solution.
// m_cells[x][y].first is the state of a cell.
// m_cells[x][y].second is the region of a cell.
// (If the state is unknown, the region is empty.)
vector<vector<pair<State, shared_ptr<Region>>>> m_cells;
// The set of all regions can be traversed in linear time.
set<shared_ptr<Region>> m_regions;
// This is initially KEEP_GOING.
// If an attempt is made to fuse two numbered regions, or to mark an already known cell,
// this is set to CONTRADICTION_FOUND.
SitRep m_sitrep;
// This stores the output that is generated during solving, to be converted into HTML later.
vector<tuple<string, vector<vector<State>>, set<pair<int, int>>, steady_clock::time_point,
int, set<pair<int, int>>>> m_output;
// This is used to guess cells in a deterministic but pseudorandomized order.
mt19937 m_prng;
Grid(const Grid& other);
Grid& operator=(const Grid&) = delete;
};
string format_time(const steady_clock::time_point start, const steady_clock::time_point finish) {
ostringstream oss;
if (finish - start < 1ms) {
oss << duration_cast<duration<double, micro>>(finish - start).count() << " microseconds";
} else if (finish - start < 1s) {
oss << duration_cast<duration<double, milli>>(finish - start).count() << " milliseconds";
} else {
oss << duration_cast<duration<double>>(finish - start).count() << " seconds";
}
return oss.str();
}
int main() {
struct Puzzle {
const char * name;
int w;
int h;
const char * s;
};
const array<Puzzle, 1> puzzles = { {
{
"grumphunt-prequel", 12, 12,
" \n"
" 1 2 6 \n"
" 3 \n"
" 5 \n"
" 2 5 \n"
" 2 \n"
" 1 \n"
" 3 5 \n"
" 5 \n"
" 6 \n"
" 1 1 9 \n"
" \n"
}
} };
try {
for (const auto& puzzle : puzzles) {
const auto start = steady_clock::now();
Grid g(puzzle.w, puzzle.h, puzzle.s);
while (g.solve() == Grid::KEEP_GOING) { }
const auto finish = steady_clock::now();
ofstream f(puzzle.name + string(".html"));
g.write(f, start, finish);
cout << puzzle.name << ": " << format_time(start, finish) << ", ";
const int k = g.known();
const int cells = puzzle.w * puzzle.h;
cout << k << "/" << cells << " (" << k * 100.0 / cells << "%) solved" << endl;
}
} catch (const exception& e) {
cerr << "EXCEPTION CAUGHT! \"" << e.what() << "\"" << endl;
return EXIT_FAILURE;
} catch (...) {
cerr << "UNKNOWN EXCEPTION CAUGHT!" << endl;
return EXIT_FAILURE;
}
}
Grid::Grid(const int width, const int height, const string& s)
: m_width(width), m_height(height), m_total_black(width * height),
m_cells(), m_regions(), m_sitrep(KEEP_GOING), m_output(), m_prng(1729) {
// Validate width and height.
if (width < 1) {
throw runtime_error("RUNTIME ERROR: Grid::Grid() - width must be at least 1.");
}
if (height < 1) {
throw runtime_error("RUNTIME ERROR: Grid::Grid() - height must be at least 1.");
}
// Initialize m_cells. We must set everything to UNKNOWN before calling add_region() below.
m_cells.resize(width, vector<pair<State, shared_ptr<Region>>>(
height, make_pair(UNKNOWN, shared_ptr<Region>())));
// Parse the string.
vector<int> v;
const regex r(R"((\d+)|( )|(\n)|[^\d \n])");
for (sregex_iterator i(s.begin(), s.end(), r), end; i != end; ++i) {
const smatch& m = *i;
if (m[1].matched) {
v.push_back(stoi(m[1]));
} else if (m[2].matched) {
v.push_back(0);
} else if (m[3].matched) {
// Do nothing.
} else {
throw runtime_error("RUNTIME ERROR: Grid::Grid() - "
"s must contain only digits, spaces, and newlines.");
}
}
// Validate the number of cells. Note that we can't do this before
// parsing, because numbers 10 and above occupy multiple characters.
if (v.size() != static_cast<size_t>(width * height)) {
throw runtime_error("RUNTIME ERROR: Grid::Grid() - "
"s must contain width * height numbers and spaces.");
}
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
const int n = v[x + y * width];
if (n > 0) {
// Testing x - 1 and x + 1 is unnecessary because
// horizontally adjacent numbers would have been concatenated.
// Testing y + 1 is unnecessary because if there are
// vertically adjacent numbers, one's above and one's below.
if (valid(x, y - 1) && cell(x, y - 1) > 0) {
throw runtime_error("RUNTIME ERROR: Grid::Grid() - "
"s contains vertically adjacent numbers.");
}
// Set the cell's state and region.
cell(x, y) = static_cast<State>(n);
add_region(x, y);
// m_total_black is width * height - (sum of all numbered cells).
// Calculating this allows us to determine whether black regions
// are partial or complete with a simple size test.
// Humans are capable of this but it's not convenient for them.
m_total_black -= n;
}
}
}
print("I'm okay to go!");
}
Grid::SitRep Grid::solve(const bool verbose, const bool guessing) {
cache_map_t cache;
// See if we're done. Before declaring victory, look for contradictions.
if (known() == m_width * m_height) {
if (detect_contradictions(verbose, cache)) {
return CONTRADICTION_FOUND;
}
if (verbose) {
print("I'm done!");
}
return SOLUTION_FOUND;
}
// Run increasingly expensive steps of analysis.
// Return as soon as one succeeds.
// Running detect_contradictions() just before analyze_confinement() increases performance.
// detect_contradictions() is moderately expensive, so it should be run after extremely cheap
// steps of analysis. However, detect_contradictions() accelerates analyze_confinement(),
// which is even more expensive. This doesn't affect correctness:
// * We always run detect_contradictions() before declaring victory.
// * The other steps of analysis are robust; if they attempt to fuse two numbered regions
// or mark an already known cell, they bail out early.
// * analyze_confinement() can still assume that it has a cache.
if (analyze_complete_islands(verbose)
|| analyze_single_liberties(verbose)
|| analyze_dual_liberties(verbose)
|| analyze_unreachable_cells(verbose)
|| analyze_potential_pools(verbose)
|| detect_contradictions(verbose, cache)
|| analyze_confinement(verbose, cache)
|| (guessing && analyze_hypotheticals(verbose))) {
return m_sitrep;
}
if (verbose) {
print("I'm stumped!");
}
return CANNOT_PROCEED;
}
// Look for complete islands.
bool Grid::analyze_complete_islands(const bool verbose) {
set<pair<int, int>> mark_as_black;
set<pair<int, int>> mark_as_white;
for (const auto& sp : m_regions) {
const Region& r = *sp;
if (r.numbered() && r.size() == r.number()) {
mark_as_black.insert(r.unk_begin(), r.unk_end());
}
}
return process(verbose, mark_as_black, mark_as_white, "Complete islands found.");
}
// Look for partial regions that can expand into only one cell. They must expand.
bool Grid::analyze_single_liberties(const bool verbose) {
set<pair<int, int>> mark_as_black;
set<pair<int, int>> mark_as_white;
for (const auto& sp : m_regions) {
const Region& r = *sp;
const bool partial =
(r.black() && r.size() < m_total_black)
|| r.white()
|| (r.numbered() && r.size() < r.number());
if (partial && r.unk_size() == 1) {
if (r.black()) {
mark_as_black.insert(*r.unk_begin());
} else {
mark_as_white.insert(*r.unk_begin());
}
}
}
return process(verbose, mark_as_black, mark_as_white,
"Expanded partial regions with only one liberty.");
}
// Look for N - 1 islands with exactly two diagonal liberties.
bool Grid::analyze_dual_liberties(const bool verbose) {
set<pair<int, int>> mark_as_black;
set<pair<int, int>> mark_as_white;
for (const auto& sp : m_regions) {
const Region& r = *sp;
if (r.numbered() && r.size() == r.number() - 1 && r.unk_size() == 2) {
const int x1 = r.unk_begin()->first;
const int y1 = r.unk_begin()->second;
const int x2 = next(r.unk_begin())->first;
const int y2 = next(r.unk_begin())->second;
if (abs(x1 - x2) == 1 && abs(y1 - y2) == 1) {
pair<int, int> p;
if (r.contains(x1, y2)) {
p = make_pair(x2, y1);
} else {
p = make_pair(x1, y2);
}
// The far cell might already be black, in which case there's nothing to do.
// It could even be white/numbered (if it's part of this island), in which case
// there's still nothing to do.
// (If it's white/numbered and not part of this island,
// we'll eventually detect a contradiction.)
if (cell(p.first, p.second) == UNKNOWN) {
mark_as_black.insert(p);
}
}
}
}
return process(verbose, mark_as_black, mark_as_white,
"N - 1 islands with exactly two diagonal liberties found.");
}
// Look for unreachable cells. They must be black.
// This supersedes complete island analysis and forbidden bridge analysis.
// (We run complete island analysis above because it's fast
// and it makes the output easier to understand.)
bool Grid::analyze_unreachable_cells(const bool verbose) {
set<pair<int, int>> mark_as_black;
set<pair<int, int>> mark_as_white;
for (int x = 0; x < m_width; ++x) {
for (int y = 0; y < m_height; ++y) {
if (unreachable(x, y)) {
mark_as_black.insert(make_pair(x, y));
}
}
}
return process(verbose, mark_as_black, mark_as_white, "Unreachable cells blackened.");
}
// Look for squares of one unknown and three black cells, or two unknown and two black cells.
bool Grid::analyze_potential_pools(const bool verbose) {
set<pair<int, int>> mark_as_black;
set<pair<int, int>> mark_as_white;
for (int x = 0; x < m_width - 1; ++x) {
for (int y = 0; y < m_height - 1; ++y) {
struct XYState {
int x;
int y;
State state;
};
array<XYState, 4> a = { {
{ x, y, cell(x, y) },
{ x + 1, y, cell(x + 1, y) },
{ x, y + 1, cell(x, y + 1) },
{ x + 1, y + 1, cell(x + 1, y + 1) }
} };
static_assert(UNKNOWN < BLACK, "This code assumes that UNKNOWN < BLACK.");
sort(a.begin(), a.end(), [](const XYState& l, const XYState& r) {
return l.state < r.state;
});
if (a[0].state == UNKNOWN
&& a[1].state == BLACK
&& a[2].state == BLACK
&& a[3].state == BLACK) {
mark_as_white.insert(make_pair(a[0].x, a[0].y));
} else if (a[0].state == UNKNOWN
&& a[1].state == UNKNOWN
&& a[2].state == BLACK
&& a[3].state == BLACK) {
for (int i = 0; i < 2; ++i) {
set<pair<int, int>> imagine_black;
imagine_black.insert(make_pair(a[0].x, a[0].y));
if (unreachable(a[1].x, a[1].y, imagine_black)) {
mark_as_white.insert(make_pair(a[0].x, a[0].y));
}
std::swap(a[0], a[1]);
}
}
}
}
return process(verbose, mark_as_black, mark_as_white, "Whitened cells to prevent pools.");
}
// A region would be "confined" if it could not be completed.
// Black regions need to consume m_total_black cells.
// White regions need to escape to a number.
// Numbered regions need to consume N cells.
// Confinement analysis consists of imagining what would happen if a particular unknown cell
// were black or white. If that would cause any region to be confined, the unknown cell
// must be the opposite color.
// Black cells can't confine black regions, obviously.
// Black cells can confine white regions, by isolating them.
// Black cells can confine numbered regions, by confining them to an insufficiently large space.
// White cells can confine black regions, by confining them to an insufficiently large space.
// (Humans look for isolation here, i.e. permanently separated black regions.
// That's harder for us to detect, but counting cells is similarly powerful.)
// White cells can't confine white regions.
// (This is true for freestanding white cells, white cells added to other white regions,
// and white cells added to numbered regions.)
// White cells can confine numbered regions, when added to other numbered regions.
// This is the most complicated case to analyze. For example:
// ####3
// #6 xXx
// #. x
// ######
// Imagining cell 'X' to be white additionally prevents region 6 from consuming
// three 'x' cells. (This is true regardless of what other cells region 3 would
// eventually occupy.)
bool Grid::analyze_confinement(const bool verbose, cache_map_t& cache) {
set<pair<int, int>> mark_as_black;
set<pair<int, int>> mark_as_white;
for (int x = 0; x < m_width; ++x) {
for (int y = 0; y < m_height; ++y) {
if (cell(x, y) == UNKNOWN) {
set<pair<int, int>> verboten;
verboten.insert(make_pair(x, y));
for (const auto& sp : m_regions) {
const Region& r = *sp;
if (confined(sp, cache, verboten)) {
if (r.black()) {
mark_as_black.insert(make_pair(x, y));
} else {
mark_as_white.insert(make_pair(x, y));
}
}
}
}
}
}
for (const auto& sp1 : m_regions) {
const Region& r = *sp1;
if (r.numbered() && r.size() < r.number()) {
for (auto u = r.unk_begin(); u != r.unk_end(); ++u) {
set<pair<int, int>> verboten;
verboten.insert(*u);
insert_valid_unknown_neighbors(verboten, u->first, u->second);
for (const auto& sp2 : m_regions) {
if (sp2 != sp1 && sp2->numbered() && confined(sp2, cache, verboten)) {
mark_as_black.insert(*u);
}
}
}
}
}
return process(verbose, mark_as_black, mark_as_white, "Confinement analysis succeeded.");
}
// Guess cells in a deterministic but pseudorandomized order.
// This attempts to avoid repeatedly guessing cells that won't get us anywhere.
// Prioritize guesses near white cells, which appears to be an especially good heuristic.
// (In particular, it appears to be better than prioritizing guesses near white regions.)
// Manhattan distance appears to work well; see https://en.wikipedia.org/wiki/Taxicab_geometry
vector<pair<int, int>> Grid::guessing_order() {
// Find all unknown cells and all white cells.
// The greatest possible Manhattan distance on the grid is m_width - 1 + m_height - 1,
// so we use m_width + m_height as an extremely large placeholder.
vector<tuple<int, int, int>> x_y_manhattan;
vector<pair<int, int>> white_cells;
for (int x = 0; x < m_width; ++x) {
for (int y = 0; y < m_height; ++y) {
switch (cell(x, y)) {
case UNKNOWN:
x_y_manhattan.push_back(make_tuple(x, y, m_width + m_height));
break;
case WHITE:
white_cells.push_back(make_pair(x, y));
break;
default:
break;
}
}
}
// Randomly shuffle the unknown cells.
shuffle(x_y_manhattan.begin(), x_y_manhattan.end(), m_prng);
// Determine the Manhattan distance from each unknown cell to the nearest white cell.
// There's probably a cleverer algorithm for this.
for (auto& [ x1, y1, manhattan ] : x_y_manhattan) {
for (const auto& [ x2, y2 ] : white_cells) {
manhattan = min(manhattan, abs(x1 - x2) + abs(y1 - y2));
}
}
// Prioritize the unknown cells by the Manhattan distance to the nearest white cell.
// stable_sort() avoids disrupting the random_shuffle() above.
stable_sort(x_y_manhattan.begin(), x_y_manhattan.end(),
[](const tuple<int, int, int>& l, const tuple<int, int, int>& r) {
return get<2>(l) < get<2>(r);
});
vector<pair<int, int>> ret(x_y_manhattan.size());
transform(x_y_manhattan.begin(), x_y_manhattan.end(), ret.begin(),
[](const tuple<int, int, int>& t) { return make_pair(get<0>(t), get<1>(t)); });
return ret;
}
bool Grid::analyze_hypotheticals(const bool verbose) {
set<pair<int, int>> mark_as_black;
set<pair<int, int>> mark_as_white;
const vector<pair<int, int>> v = guessing_order();
int failed_guesses = 0;
set<pair<int, int>> failed_coords;
for (const auto& [ x, y ] : v) {
for (int i = 0; i < 2; ++i) {
const State color = i == 0 ? BLACK : WHITE;
auto& mark_as_diff = i == 0 ? mark_as_white : mark_as_black;
auto& mark_as_same = i == 0 ? mark_as_black : mark_as_white;
Grid other(*this);
other.mark(color, x, y);
SitRep sr = KEEP_GOING;
while (sr == KEEP_GOING) {
sr = other.solve(false, false);
}
if (sr == CONTRADICTION_FOUND) {
mark_as_diff.insert(make_pair(x, y));
return process(verbose, mark_as_black, mark_as_white,
"Hypothetical contradiction found.", failed_guesses, failed_coords);
}
if (sr == SOLUTION_FOUND) {
mark_as_same.insert(make_pair(x, y));
return process(verbose, mark_as_black, mark_as_white,
"Hypothetical solution found.", failed_guesses, failed_coords);
}
// sr == CANNOT_PROCEED
++failed_guesses;
failed_coords.insert(make_pair(x, y));
}
}
return false;
}
int Grid::known() const {
int ret = 0;
for (int x = 0; x < m_width; ++x) {
for (int y = 0; y < m_height; ++y) {
if (cell(x, y) != UNKNOWN) {
++ret;
}
}
}
return ret;
}
void Grid::write(ostream& os, const steady_clock::time_point start, const steady_clock::time_point finish) const {
os <<
R"(<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<style>
body {
font-family: Verdana, sans-serif;
line-height: 1.4;
}
table {
border: solid 3px #000000;
border-collapse: collapse;
}
td {
border: solid 1px #000000;
text-align: center;
width: 20px;
height: 20px;
}
td.unknown { background-color: #C0C0C0; }
td.white.new { background-color: #FFFF00; }
td.white.old { }
td.black.new { background-color: #008080; }
td.black.old { background-color: #808080; }
td.number { }
td.failed { border: solid 3px #000000; }
</style>
<title>Nurikabe</title>
</head>
<body>
)";
steady_clock::time_point old_ctr = start;
for (const auto& [ s, v, updated, ctr, failed_guesses, failed_coords ] : m_output) {
os << s << " (" << format_time(old_ctr, ctr) << ")\n";
if (failed_guesses == 1) {
os << "<br/>1 guess failed.\n";
} else if (failed_guesses > 0) {
os << "<br/>" << failed_guesses << " guesses failed.\n";
}
old_ctr = ctr;
os << "<table>\n";
for (int y = 0; y < m_height; ++y) {
os << "<tr>";
for (int x = 0; x < m_width; ++x) {
os << "<td class=\"";
os << (updated.find(make_pair(x, y)) != updated.end() ? "new " : "old ");
if (failed_coords.find(make_pair(x, y)) != failed_coords.end()) {
os << "failed ";
}
switch (v[x][y]) {
case UNKNOWN: os << "unknown\"> "; break;
case WHITE: os << "white\">."; break;
case BLACK: os << "black\">#"; break;
default: os << "number\">" << v[x][y]; break;
}
os << "</td>";
}
os << "</tr>\n";
}
os << "</table><br/>\n";
}
os << "Total: " << format_time(start, finish) << "\n";
os <<
" </body>\n"
"</html>\n";
}
bool Grid::valid(const int x, const int y) const {
return x >= 0 && x < m_width && y >= 0 && y < m_height;
}
Grid::State& Grid::cell(const int x, const int y) {
return m_cells[x][y].first;
}
const Grid::State& Grid::cell(const int x, const int y) const {
return m_cells[x][y].first;
}
shared_ptr<Grid::Region>& Grid::region(const int x, const int y) {
return m_cells[x][y].second;
}
const shared_ptr<Grid::Region>& Grid::region(const int x, const int y) const {
return m_cells[x][y].second;
}
void Grid::print(const string& s, const set<pair<int, int>>& updated,
const int failed_guesses, const set<pair<int, int>>& failed_coords) {
vector<vector<State>> v(m_width, vector<State>(m_height));
for (int x = 0; x < m_width; ++x) {
for (int y = 0; y < m_height; ++y) {
v[x][y] = cell(x, y);
}
}
m_output.push_back(make_tuple(s, v, updated, steady_clock::now(), failed_guesses, failed_coords));
}
bool Grid::process(const bool verbose, const set<pair<int, int>>& mark_as_black,
const set<pair<int, int>>& mark_as_white, const string& s,
const int failed_guesses, const set<pair<int, int>>& failed_coords) {
if (mark_as_black.empty() && mark_as_white.empty()) {
return false;
}
for (const auto& [ x, y ] : mark_as_black) {
mark(BLACK, x, y);
}
for (const auto& [ x, y ] : mark_as_white) {
mark(WHITE, x, y);
}
if (verbose) {
set<pair<int, int>> updated(mark_as_black);
updated.insert(mark_as_white.begin(), mark_as_white.end());
string t = s;
if (m_sitrep == CONTRADICTION_FOUND) {
t += " (Contradiction found! Attempted to fuse two numbered regions"
" or mark an already known cell.)";
}
print(t, updated, failed_guesses, failed_coords);
}
return true;
}
template <typename F> void Grid::for_valid_neighbors(const int x, const int y, F f) const {
if (x > 0) {
f(x - 1, y);
}
if (x + 1 < m_width) {
f(x + 1, y);
}
if (y > 0) {
f(x, y - 1);
}
if (y + 1 < m_height) {
f(x, y + 1);
}
}
void Grid::insert_valid_neighbors(set<pair<int, int>>& s, const int x, const int y) const {
for_valid_neighbors(x, y, [&](const int a, const int b) {
s.insert(make_pair(a, b));
});
}
void Grid::insert_valid_unknown_neighbors(set<pair<int, int>>& s, const int x, const int y) const {
for_valid_neighbors(x, y, [&](const int a, const int b) {
if (cell(a, b) == UNKNOWN) {
s.insert(make_pair(a, b));
}
});
}
void Grid::add_region(const int x, const int y) {
// Construct a region, then add it to the cell and the set of all regions.
set<pair<int, int>> unknowns;
insert_valid_unknown_neighbors(unknowns, x, y);
auto r = make_shared<Region>(cell(x, y), x, y, unknowns);
region(x, y) = r;
m_regions.insert(r);
}
void Grid::mark(const State s, const int x, const int y) {
if (s != WHITE && s != BLACK) {
throw logic_error("LOGIC ERROR: Grid::mark() - s must be either WHITE or BLACK.");
}
// If we're asked to mark an already known cell, we've encountered a contradiction.
// Remember this, so that solve() can report the contradiction.
if (cell(x, y) != UNKNOWN) {
m_sitrep = CONTRADICTION_FOUND;
return;
}
// Set the cell's new state. Because it's now known,
// update each region's set of surrounding unknown cells.
cell(x, y) = s;
for (const auto& sp : m_regions) {
sp->unk_erase(x, y);
}
// Marking a cell as white or black could create an independent region,
// could be added to an existing region, or could connect 2, 3, or 4 separate regions.
// The easiest thing to do is to create a region for this cell,