Using depth-first search and propagation, try all possible values.
(values)
| 154 | |
| 155 | |
| 156 | def search(values): |
| 157 | """ |
| 158 | Using depth-first search and propagation, try all possible values. |
| 159 | """ |
| 160 | if values is False: |
| 161 | return False ## Failed earlier |
| 162 | if all(len(values[s]) == 1 for s in squares): |
| 163 | return values ## Solved! |
| 164 | ## Chose the unfilled square s with the fewest possibilities |
| 165 | _n, s = min((len(values[s]), s) for s in squares if len(values[s]) > 1) |
| 166 | return some(search(assign(values.copy(), s, d)) for d in values[s]) |
| 167 | |
| 168 | |
| 169 | def solve_all(grids, name="", showif=0.0): |