solver.py (26202B)
1 from __future__ import annotations 2 3 from dataclasses import dataclass 4 from collections import deque 5 import math 6 from typing import Iterable 7 8 from .board import BoardSnapshot, Cell 9 10 11 @dataclass 12 class SolveResult: 13 to_click: set[Cell] 14 to_flag: set[Cell] 15 guess: Cell | None 16 guess_prob: float | None 17 18 19 def _adjacent_sets(board: BoardSnapshot, cell: Cell) -> tuple[set[Cell], set[Cell], int]: 20 covered: set[Cell] = set() 21 flagged: set[Cell] = set() 22 for n in board.neighbors(cell): 23 v = board.get(n) 24 if v == "covered": 25 covered.add(n) 26 elif v == "flagged": 27 flagged.add(n) 28 return covered, flagged, len(flagged) 29 30 31 def _basic_deductions(board: BoardSnapshot) -> tuple[set[Cell], set[Cell]]: 32 safe: set[Cell] = set() 33 mines: set[Cell] = set() 34 35 for cell, number in board.number_cells().items(): 36 # Include 0: if a cell shows 0, all adjacent covered cells are safe. 37 covered, flagged, flagged_count = _adjacent_sets(board, cell) 38 if not covered: 39 continue 40 if number == flagged_count: 41 safe |= covered 42 if number == flagged_count + len(covered): 43 mines |= covered 44 safe -= board.flagged_cells() 45 mines -= board.flagged_cells() 46 return safe, mines 47 48 49 def _subset_deductions(board: BoardSnapshot) -> tuple[set[Cell], set[Cell]]: 50 safe: set[Cell] = set() 51 mines: set[Cell] = set() 52 53 numbered = [(c, n) for c, n in board.number_cells().items() if n > 0] 54 per_cell: dict[Cell, tuple[set[Cell], int]] = {} 55 for c, n in numbered: 56 covered, _flagged, flagged_count = _adjacent_sets(board, c) 57 need = n - flagged_count 58 if need < 0 or not covered: 59 continue 60 per_cell[c] = (covered, need) 61 62 items = list(per_cell.items()) 63 for i in range(len(items)): 64 a_cell, (a_set, a_need) = items[i] 65 for j in range(i + 1, len(items)): 66 b_cell, (b_set, b_need) = items[j] 67 if a_set == b_set or not a_set or not b_set: 68 continue 69 if a_set.issubset(b_set): 70 diff = b_set - a_set 71 mines_in_diff = b_need - a_need 72 elif b_set.issubset(a_set): 73 diff = a_set - b_set 74 mines_in_diff = a_need - b_need 75 else: 76 continue 77 78 if mines_in_diff == 0: 79 safe |= diff 80 elif mines_in_diff == len(diff): 81 mines |= diff 82 83 safe -= board.flagged_cells() 84 mines -= board.flagged_cells() 85 return safe, mines 86 87 88 def _pattern_121_1221(board: BoardSnapshot) -> tuple[set[Cell], set[Cell]]: 89 safe: set[Cell] = set() 90 mines: set[Cell] = set() 91 nums = board.number_cells() 92 93 def is_open_or_oob(c: Cell) -> bool: 94 if not board.in_bounds(c): 95 return True 96 v = board.get(c) 97 return v != "covered" and v != "unknown" 98 99 def is_covered(c: Cell) -> bool: 100 return board.in_bounds(c) and board.get(c) == "covered" 101 102 # Horizontal and vertical orientations; we only apply when the pattern borders 103 # a single strip of covered cells (edge-like situation). 104 for y in range(board.min_y, board.max_y + 1): 105 for x in range(board.min_x, board.max_x + 1): 106 c0 = Cell(x, y) 107 if nums.get(c0) != 1: 108 continue 109 110 # 1-2-1 horizontal 111 c1 = Cell(x + 1, y) 112 c2 = Cell(x + 2, y) 113 if board.in_bounds(c2) and nums.get(c1) == 2 and nums.get(c2) == 1: 114 for dy in (-1, 1): 115 strip = [Cell(x + k, y + dy) for k in range(3)] 116 other = [Cell(x + k, y - dy) for k in range(3)] 117 if all(is_covered(s) for s in strip) and all(is_open_or_oob(o) for o in other): 118 mines.add(strip[0]) 119 mines.add(strip[2]) 120 safe.add(strip[1]) 121 122 # 1-2-2-1 horizontal 123 c3 = Cell(x + 3, y) 124 if board.in_bounds(c3) and nums.get(c1) == 2 and nums.get(c2) == 2 and nums.get(c3) == 1: 125 for dy in (-1, 1): 126 strip = [Cell(x + k, y + dy) for k in range(4)] 127 other = [Cell(x + k, y - dy) for k in range(4)] 128 if all(is_covered(s) for s in strip) and all(is_open_or_oob(o) for o in other): 129 safe.add(strip[0]) 130 safe.add(strip[3]) 131 mines.add(strip[1]) 132 mines.add(strip[2]) 133 134 for x in range(board.min_x, board.max_x + 1): 135 for y in range(board.min_y, board.max_y + 1): 136 c0 = Cell(x, y) 137 if nums.get(c0) != 1: 138 continue 139 140 # 1-2-1 vertical 141 c1 = Cell(x, y + 1) 142 c2 = Cell(x, y + 2) 143 if board.in_bounds(c2) and nums.get(c1) == 2 and nums.get(c2) == 1: 144 for dx in (-1, 1): 145 strip = [Cell(x + dx, y + k) for k in range(3)] 146 other = [Cell(x - dx, y + k) for k in range(3)] 147 if all(is_covered(s) for s in strip) and all(is_open_or_oob(o) for o in other): 148 mines.add(strip[0]) 149 mines.add(strip[2]) 150 safe.add(strip[1]) 151 152 # 1-2-2-1 vertical 153 c3 = Cell(x, y + 3) 154 if board.in_bounds(c3) and nums.get(c1) == 2 and nums.get(c2) == 2 and nums.get(c3) == 1: 155 for dx in (-1, 1): 156 strip = [Cell(x + dx, y + k) for k in range(4)] 157 other = [Cell(x - dx, y + k) for k in range(4)] 158 if all(is_covered(s) for s in strip) and all(is_open_or_oob(o) for o in other): 159 safe.add(strip[0]) 160 safe.add(strip[3]) 161 mines.add(strip[1]) 162 mines.add(strip[2]) 163 164 safe -= board.flagged_cells() 165 mines -= board.flagged_cells() 166 return safe, mines 167 168 169 @dataclass(frozen=True) 170 class Constraint: 171 cells: frozenset[Cell] 172 mines: int 173 174 175 def _frontier_constraints(board: BoardSnapshot) -> tuple[set[Cell], list[Constraint]]: 176 frontier: set[Cell] = set() 177 constraints: list[Constraint] = [] 178 for cell, number in board.number_cells().items(): 179 if number <= 0: 180 continue 181 covered, _flagged, flagged_count = _adjacent_sets(board, cell) 182 if not covered: 183 continue 184 needed = number - flagged_count 185 if needed < 0: 186 continue 187 frontier |= covered 188 constraints.append(Constraint(frozenset(covered), needed)) 189 return frontier, constraints 190 191 192 def _components(frontier: set[Cell], constraints: list[Constraint]) -> list[tuple[list[Cell], list[Constraint]]]: 193 parent: dict[Cell, Cell] = {c: c for c in frontier} 194 195 def find(c: Cell) -> Cell: 196 while parent[c] != c: 197 parent[c] = parent[parent[c]] 198 c = parent[c] 199 return c 200 201 def union(a: Cell, b: Cell) -> None: 202 ra, rb = find(a), find(b) 203 if ra != rb: 204 parent[rb] = ra 205 206 for con in constraints: 207 cells = list(con.cells) 208 for i in range(1, len(cells)): 209 union(cells[0], cells[i]) 210 211 groups: dict[Cell, set[Cell]] = {} 212 for c in frontier: 213 groups.setdefault(find(c), set()).add(c) 214 215 out: list[tuple[list[Cell], list[Constraint]]] = [] 216 for root, cells in groups.items(): 217 cell_set = set(cells) 218 cons = [con for con in constraints if con.cells & cell_set] 219 out.append((sorted(cells, key=lambda z: (z.y, z.x)), cons)) 220 return out 221 222 223 def _enumerate_component( 224 variables: list[Cell], 225 constraints: list[Constraint], 226 max_solutions: int = 200_000, 227 ) -> tuple[int, dict[Cell, int]]: 228 idx = {c: i for i, c in enumerate(variables)} 229 cons_vars: list[list[int]] = [[idx[c] for c in con.cells if c in idx] for con in constraints] 230 cons_need: list[int] = [con.mines for con in constraints] 231 232 # Track current assigned mines count per constraint and remaining unassigned. 233 cons_assigned = [0] * len(constraints) 234 cons_remaining = [len(vs) for vs in cons_vars] 235 mines_per_cell = {c: 0 for c in variables} 236 total = 0 237 238 # Precompute which constraints each variable affects. 239 var_to_cons: list[list[int]] = [[] for _ in variables] 240 for ci, vs in enumerate(cons_vars): 241 for vi in vs: 242 var_to_cons[vi].append(ci) 243 244 assignment = [0] * len(variables) 245 # Heuristic ordering: assign most constrained variables first for better pruning. 246 order = sorted(range(len(variables)), key=lambda vi: len(var_to_cons[vi]), reverse=True) 247 248 def feasible() -> bool: 249 for ci in range(len(constraints)): 250 need = cons_need[ci] 251 assigned = cons_assigned[ci] 252 remaining = cons_remaining[ci] 253 if assigned > need: 254 return False 255 if assigned + remaining < need: 256 return False 257 return True 258 259 def backtrack(i: int) -> None: 260 nonlocal total 261 if total >= max_solutions: 262 return 263 if i == len(variables): 264 if all(cons_assigned[ci] == cons_need[ci] for ci in range(len(constraints))): 265 total += 1 266 for vi, val in enumerate(assignment): 267 if val: 268 mines_per_cell[variables[vi]] += 1 269 return 270 271 vi = order[i] 272 # Try safe then mine to bias towards fewer mines for early pruning. 273 for val in (0, 1): 274 assignment[vi] = val 275 touched = var_to_cons[vi] 276 for ci in touched: 277 cons_remaining[ci] -= 1 278 cons_assigned[ci] += val 279 if feasible(): 280 backtrack(i + 1) 281 for ci in touched: 282 cons_assigned[ci] -= val 283 cons_remaining[ci] += 1 284 assignment[vi] = 0 285 286 backtrack(0) 287 return total, mines_per_cell 288 289 290 def _enumerate_component_hist( 291 variables: list[Cell], 292 constraints: list[Constraint], 293 max_solutions: int = 200_000, 294 ) -> tuple[dict[int, int], dict[Cell, dict[int, int]]]: 295 """ 296 Enumerate satisfying assignments for a component and return: 297 - counts[m] = number of solutions with exactly m mines in this component 298 - per_cell_counts[cell][m] = number of solutions where cell is a mine AND total mines is m 299 """ 300 idx = {c: i for i, c in enumerate(variables)} 301 cons_vars: list[list[int]] = [[idx[c] for c in con.cells if c in idx] for con in constraints] 302 cons_need: list[int] = [con.mines for con in constraints] 303 304 cons_assigned = [0] * len(constraints) 305 cons_remaining = [len(vs) for vs in cons_vars] 306 counts: dict[int, int] = {} 307 per_cell: dict[Cell, dict[int, int]] = {c: {} for c in variables} 308 309 var_to_cons: list[list[int]] = [[] for _ in variables] 310 for ci, vs in enumerate(cons_vars): 311 for vi in vs: 312 var_to_cons[vi].append(ci) 313 314 order = sorted(range(len(variables)), key=lambda vi: len(var_to_cons[vi]), reverse=True) 315 assignment = [0] * len(variables) 316 total = 0 317 318 def feasible() -> bool: 319 for ci in range(len(constraints)): 320 need = cons_need[ci] 321 assigned = cons_assigned[ci] 322 remaining = cons_remaining[ci] 323 if assigned > need: 324 return False 325 if assigned + remaining < need: 326 return False 327 return True 328 329 def backtrack(i: int, mine_count: int) -> None: 330 nonlocal total 331 if total >= max_solutions: 332 return 333 if i == len(variables): 334 if all(cons_assigned[ci] == cons_need[ci] for ci in range(len(constraints))): 335 total += 1 336 counts[mine_count] = counts.get(mine_count, 0) + 1 337 for vi, val in enumerate(assignment): 338 if val: 339 cell = variables[vi] 340 d = per_cell[cell] 341 d[mine_count] = d.get(mine_count, 0) + 1 342 return 343 344 vi = order[i] 345 for val in (0, 1): 346 assignment[vi] = val 347 touched = var_to_cons[vi] 348 for ci in touched: 349 cons_remaining[ci] -= 1 350 cons_assigned[ci] += val 351 if feasible(): 352 backtrack(i + 1, mine_count + val) 353 for ci in touched: 354 cons_assigned[ci] -= val 355 cons_remaining[ci] += 1 356 assignment[vi] = 0 357 358 backtrack(0, 0) 359 return counts, per_cell 360 361 362 def _nCk(n: int, k: int) -> int: 363 if k < 0 or k > n: 364 return 0 365 return math.comb(n, k) 366 367 368 def _probability_guess( 369 board: BoardSnapshot, 370 total_mines: int, 371 component_limit: int = 24, 372 ) -> tuple[Cell | None, float | None, set[Cell], set[Cell]]: 373 covered_all = {c for c in board.iter_cells() if board.get(c) == "covered"} 374 flagged = board.flagged_cells() 375 mines_left = max(0, total_mines - len(flagged)) 376 377 frontier, constraints = _frontier_constraints(board) 378 safe: set[Cell] = set() 379 mines: set[Cell] = set() 380 381 probs: dict[Cell, float] = {} 382 unconstrained = covered_all - frontier - flagged 383 384 def heuristic_prob_for_frontier_cell(cell: Cell) -> float | None: 385 # Cheap local estimate for cells in large frontier components that we 386 # don't enumerate: look at each adjacent revealed number constraint and 387 # estimate mine chance as (mines_needed / covered_neighbors_count). 388 estimates: list[float] = [] 389 for n in board.neighbors(cell): 390 v = board.get(n) 391 if not isinstance(v, int) or v < 0: 392 continue 393 covered, _flagged, flagged_count = _adjacent_sets(board, n) 394 if cell not in covered: 395 continue 396 need = v - flagged_count 397 if need < 0 or len(covered) == 0: 398 continue 399 estimates.append(need / len(covered)) 400 if not estimates: 401 return None 402 # Conservative-ish: use the maximum local density among adjacent constraints. 403 return max(estimates) 404 405 # Enumerate each connected frontier component (when small enough). 406 enum_components: list[tuple[list[Cell], dict[int, int], dict[Cell, dict[int, int]]]] = [] 407 for variables, cons in _components(frontier, constraints): 408 if len(variables) == 0: 409 continue 410 if len(variables) > component_limit: 411 continue 412 counts, per_cell = _enumerate_component_hist(variables, cons) 413 if sum(counts.values()) == 0: 414 continue 415 enum_components.append((variables, counts, per_cell)) 416 417 # Combine enumerated components with the global mine total to improve guessing. 418 unconstrained_count = len(unconstrained) 419 if enum_components: 420 # dp_all[sum_mines] = number of ways across components to realize that sum. 421 dp_all: dict[int, int] = {0: 1} 422 for _vars, counts, _per_cell in enum_components: 423 new: dict[int, int] = {} 424 for s, ways_s in dp_all.items(): 425 for m, ways_m in counts.items(): 426 new[s + m] = new.get(s + m, 0) + ways_s * ways_m 427 dp_all = new 428 429 total_ways = 0 430 for s, ways_s in dp_all.items(): 431 total_ways += ways_s * _nCk(unconstrained_count, mines_left - s) 432 433 if total_ways > 0: 434 # Build prefix/suffix DPs so we can compute "other components" efficiently. 435 prefix: list[dict[int, int]] = [{0: 1}] 436 for _vars, counts, _per_cell in enum_components: 437 prev = prefix[-1] 438 cur: dict[int, int] = {} 439 for s, ways_s in prev.items(): 440 for m, ways_m in counts.items(): 441 cur[s + m] = cur.get(s + m, 0) + ways_s * ways_m 442 prefix.append(cur) 443 444 suffix: list[dict[int, int]] = [{0: 1} for _ in range(len(enum_components) + 1)] 445 suffix[-1] = {0: 1} 446 for i in range(len(enum_components) - 1, -1, -1): 447 nxt = suffix[i + 1] 448 counts = enum_components[i][1] 449 cur: dict[int, int] = {} 450 for s, ways_s in nxt.items(): 451 for m, ways_m in counts.items(): 452 cur[s + m] = cur.get(s + m, 0) + ways_s * ways_m 453 suffix[i] = cur 454 455 for i, (_vars, counts_i, per_cell_i) in enumerate(enum_components): 456 # other_dp = convolution(prefix[i], suffix[i+1]) 457 other_dp: dict[int, int] = {} 458 for s1, w1 in prefix[i].items(): 459 for s2, w2 in suffix[i + 1].items(): 460 other_dp[s1 + s2] = other_dp.get(s1 + s2, 0) + w1 * w2 461 462 # Precompute weight for each m in this component (ways for the rest + unconstrained). 463 weight_for_m: dict[int, int] = {} 464 for m in counts_i.keys(): 465 w = 0 466 for s_other, ways_other in other_dp.items(): 467 w += ways_other * _nCk(unconstrained_count, mines_left - (m + s_other)) 468 weight_for_m[m] = w 469 470 for cell, hist in per_cell_i.items(): 471 mine_weight = 0 472 for m, cnt in hist.items(): 473 mine_weight += cnt * weight_for_m.get(m, 0) 474 if mine_weight == 0: 475 safe.add(cell) 476 probs[cell] = 0.0 477 elif mine_weight == total_ways: 478 mines.add(cell) 479 probs[cell] = 1.0 480 else: 481 probs[cell] = mine_weight / total_ways 482 483 # Unconstrained cells: simple global estimate. 484 remaining_covered = len(covered_all - flagged) 485 base_prob = (mines_left / remaining_covered) if remaining_covered else 1.0 486 for c in unconstrained: 487 probs[c] = base_prob 488 # Frontier cells in skipped components: fill with local heuristic estimate. 489 for c in frontier: 490 if c in flagged or c in probs: 491 continue 492 hp = heuristic_prob_for_frontier_cell(c) 493 if hp is not None: 494 probs[c] = hp 495 496 # If we have any frontier, prefer guessing *on* the frontier instead of 497 # clicking in an unrelated "sea" of covered tiles. 498 if frontier: 499 candidates = [c for c in frontier if c not in flagged and board.get(c) == "covered"] 500 else: 501 candidates = [c for c in covered_all if c not in flagged] 502 if not candidates: 503 return None, None, safe, mines 504 505 def edge_corner_bonus(c: Cell) -> float: 506 is_edge = c.x in (board.min_x, board.max_x) or c.y in (board.min_y, board.max_y) 507 is_corner = (c.x, c.y) in ( 508 (board.min_x, board.min_y), 509 (board.min_x, board.max_y), 510 (board.max_x, board.min_y), 511 (board.max_x, board.max_y), 512 ) 513 if is_corner: 514 return -0.02 515 if is_edge: 516 return -0.01 517 return 0.0 518 519 # Precompute distance-to-nearest-open for tie-breaking efficiently. 520 open_cells = [cc for cc in board.iter_cells() if isinstance(board.get(cc), int)] 521 dist_to_open: dict[Cell, int] = {} 522 if open_cells: 523 q: deque[Cell] = deque() 524 for oc in open_cells: 525 dist_to_open[oc] = 0 526 q.append(oc) 527 while q: 528 cur = q.popleft() 529 nd = dist_to_open[cur] + 1 530 for n in board.neighbors(cur): 531 if n not in dist_to_open: 532 dist_to_open[n] = nd 533 q.append(n) 534 535 def score(c: Cell) -> tuple[float, float, int, int, int, int]: 536 p = probs.get(c, base_prob) 537 # Prefer guesses that are more "connected" to the known area to reduce 538 # guess chains: more adjacent revealed numbers, then lower distance to any 539 # revealed cell. (Frontier already tends to be distance=1.) 540 adj_open = 0 541 for n in board.neighbors(c): 542 if isinstance(board.get(n), int): 543 adj_open += 1 544 545 dist = dist_to_open.get(c, 0) 546 547 return (p, p + edge_corner_bonus(c), -adj_open, dist, c.y, c.x) 548 549 best = min(candidates, key=score) 550 return best, probs.get(best, base_prob), safe, mines 551 552 553 def solve_step(board: BoardSnapshot, total_mines: int) -> SolveResult: 554 to_click: set[Cell] = set() 555 to_flag: set[Cell] = set() 556 557 virtual_flags: set[Cell] = set(board.flagged_cells()) 558 559 class _VirtualBoard: 560 def __init__(self, base: BoardSnapshot, extra_flags: set[Cell]): 561 self._base = base 562 self._extra_flags = extra_flags 563 self.origin_x = base.origin_x 564 self.origin_y = base.origin_y 565 self.width = base.width 566 self.height = base.height 567 568 @property 569 def min_x(self) -> int: 570 return self.origin_x 571 572 @property 573 def min_y(self) -> int: 574 return self.origin_y 575 576 @property 577 def max_x(self) -> int: 578 return self.origin_x + self.width - 1 579 580 @property 581 def max_y(self) -> int: 582 return self.origin_y + self.height - 1 583 584 def in_bounds(self, cell: Cell) -> bool: 585 return self._base.in_bounds(cell) 586 587 def neighbors(self, cell: Cell): 588 return self._base.neighbors(cell) 589 590 def iter_cells(self): 591 return self._base.iter_cells() 592 593 def number_cells(self): 594 return self._base.number_cells() 595 596 def flagged_cells(self) -> set[Cell]: 597 return set(self._base.flagged_cells()) | set(self._extra_flags) 598 599 def get(self, cell: Cell) -> object: 600 if cell in self._extra_flags: 601 return "flagged" 602 return self._base.get(cell) 603 604 # Propagate deterministic mine flags through the rules, since new flags can 605 # unlock new safe clicks (basic rule) without needing to open additional cells. 606 # 607 # Performance: only run the (expensive) probability/enumeration pass when the 608 # cheap local deductions have converged. 609 while True: 610 eff = _VirtualBoard(board, virtual_flags) 611 612 safe: set[Cell] = set() 613 mines: set[Cell] = set() 614 615 s, m = _basic_deductions(eff) # type: ignore[arg-type] 616 safe |= s 617 mines |= m 618 s, m = _subset_deductions(eff) # type: ignore[arg-type] 619 safe |= s 620 mines |= m 621 s, m = _pattern_121_1221(eff) # type: ignore[arg-type] 622 safe |= s 623 mines |= m 624 625 new_mines = mines - virtual_flags 626 if new_mines: 627 accepted = filter_flag_moves(board, new_mines, extra_flagged=virtual_flags) 628 accepted -= virtual_flags 629 if accepted: 630 to_flag |= accepted 631 virtual_flags |= accepted 632 to_click |= safe 633 continue 634 635 to_click |= safe 636 637 # Now that local deductions are stable, try enumeration to discover 638 # additional forced safes/mines. 639 _guess, _prob, enum_safe, enum_mines = _probability_guess(eff, total_mines=total_mines) # type: ignore[arg-type] 640 to_click |= enum_safe 641 enum_new = enum_mines - virtual_flags 642 if enum_new: 643 accepted = filter_flag_moves(board, enum_new, extra_flagged=virtual_flags) 644 accepted -= virtual_flags 645 if accepted: 646 to_flag |= accepted 647 virtual_flags |= accepted 648 continue 649 650 break 651 652 # After propagation, if there are no deterministic actions, pick a guess. 653 guess: Cell | None = None 654 prob: float | None = None 655 if not to_click and not to_flag: 656 eff = _VirtualBoard(board, virtual_flags) 657 guess, prob, _enum_safe, _enum_mines = _probability_guess(eff, total_mines=total_mines) # type: ignore[arg-type] 658 659 to_click -= board.flagged_cells() 660 to_flag -= board.flagged_cells() 661 to_click = {c for c in to_click if board.get(c) == "covered"} 662 to_flag = {c for c in to_flag if board.get(c) == "covered"} 663 return SolveResult(to_click=to_click, to_flag=to_flag, guess=guess, guess_prob=prob) 664 665 666 def best_guess(board: BoardSnapshot, total_mines: int) -> tuple[Cell | None, float | None]: 667 guess, prob, _safe, _mines = _probability_guess(board, total_mines=total_mines) 668 return guess, prob 669 670 671 def filter_flag_moves( 672 board: BoardSnapshot, 673 candidates: Iterable[Cell], 674 extra_flagged: set[Cell] | None = None, 675 ) -> set[Cell]: 676 """ 677 Defensive filter to avoid over-flagging around a revealed number. 678 679 This mainly protects against situations where multiple candidate mines touch a 680 single "1" (or any number), which would immediately contradict the visible 681 constraint and cause a false flag. 682 """ 683 nums = board.number_cells() 684 accepted: set[Cell] = set() 685 sim_flags: set[Cell] = set(board.flagged_cells()) 686 if extra_flagged: 687 sim_flags |= set(extra_flagged) 688 689 for c in iter_in_order(candidates): 690 if board.get(c) != "covered": 691 continue 692 violates = False 693 # Only check revealed number cells adjacent to the candidate. 694 for n in board.neighbors(c): 695 number = nums.get(n) 696 if number is None: 697 continue 698 flagged_after = 0 699 for nn in board.neighbors(n): 700 if nn == c or nn in sim_flags: 701 flagged_after += 1 702 else: 703 v = board.get(nn) 704 if v == "flagged": 705 flagged_after += 1 706 if flagged_after > number: 707 violates = True 708 break 709 if violates: 710 continue 711 accepted.add(c) 712 sim_flags.add(c) 713 714 return accepted 715 716 717 def choose_first_click(board: BoardSnapshot) -> Cell: 718 return Cell(board.min_x + board.width // 2, board.min_y + board.height // 2) 719 720 721 def iter_in_order(cells: Iterable[Cell]) -> list[Cell]: 722 return sorted(cells, key=lambda c: (c.y, c.x))