2018年12月26日水曜日

開発環境

最近、数独のを解くためのアルゴリズムについて考えたから、解答が気になる方、あるいは答え合わせをしたい方の参考になれば。(制約無しの場合と、対角上の制約を加えた場合。)

コード(Emacs)

Python 3

#!/usr/bin/env python3
def find_next_cell_to_fill(grid: list) -> (int, int):
    for x in range(9):
        for y in range(9):
            if grid[x][y] == 0:
                return x, y
    return -1, -1


def is_valid(grid: list, i: int, j: int, e: int) -> bool:
    if all([e != grid[i][y] for y in range(9)]) and \
       all([e != grid[x][j] for x in range(9)]):
        top_x = 3 * (i // 3)
        top_y = 3 * (j // 3)
        for x in range(top_x, top_x + 3):
            for y in range(top_y, top_y + 3):
                if grid[x][y] == e:
                    return False
        return True
    return False


def is_valid_diagonal(grid: list, i: int, j: int, e: int) -> bool:
    if i == j and not all([e != grid[x][x] for x in range(9)]):
        return False
    if all([e != grid[i][y] for y in range(9)]) and \
       all([e != grid[x][j] for x in range(9)]):
        top_x = 3 * (i // 3)
        top_y = 3 * (j // 3)
        for x in range(top_x, top_x + 3):
            for y in range(top_y, top_y + 3):
                if grid[x][y] == e:
                    return False
        return True
    return False


def make_implications(grid: list, i: int, j: int, e: int) -> list:
    sectors = [[0, 3, 0, 3], [3, 6, 0, 3], [6, 9, 0, 3],
               [0, 3, 3, 6], [3, 6, 3, 6], [6, 9, 3, 6],
               [0, 3, 6, 9], [3, 6, 6, 9], [6, 9, 6, 9]]
    grid[i][j] = e
    implications = [(i, j, e)]
    implications_len = len(implications)
    while True:
        for x1, x2, y1, y2 in sectors:
            val_set = set(range(1, 10))
            for x in range(x1, x2):
                for y in range(y1, y2):
                    if grid[x][y] != 0:
                        val_set.remove(grid[x][y])
            sector_infos = [[x, y, val_set.copy()]
                            for x in range(x1, x2)
                            for y in range(y1, y2)
                            if grid[x][y] == 0]
            for x0, y0, val_set0 in sector_infos:
                row_val = {grid[x0][y] for y in range(9)}
                left = val_set0 - row_val
                col_val = {grid[x][y0] for x in range(9)}
                left -= col_val
                if len(left) == 1:
                    val = left.pop()
                    if is_valid_diagonal(grid, x0, y0, val):
                        grid[x0][y0] = val
                        implications.append((x0, y0, val))
        if len(implications) == implications_len:
            break
        implications_len = len(implications)
    return implications


def undo_implications(grid: int, implications: list) -> None:
    for x, y, _ in implications:
        grid[x][y] = 0


backtracks = 0


def solve_sudoku(grid: list, i: int = 0, j: int = 0) -> bool:
    global backtracks
    i, j = find_next_cell_to_fill(grid)
    if i == -1:
        return True
    for e in range(1, 10):
        if is_valid(grid, i, j, e):
            implications = make_implications(grid, i, j, e)
            if solve_sudoku(grid, i, j):
                return True
            backtracks += 1
            undo_implications(grid, implications)
    return False


def solve_sudoku_diagonal(grid: list, i: int = 0, j: int = 0) -> bool:
    global backtracks
    i, j = find_next_cell_to_fill(grid)
    if i == -1:
        return True
    for e in range(1, 10):
        if is_valid_diagonal(grid, i, j, e):
            implications = make_implications(grid, i, j, e)
            if solve_sudoku_diagonal(grid, i, j):
                return True
            backtracks += 1
            undo_implications(grid, implications)
    return False


def print_sudoku(grid: list) -> None:
    print('-' * 29)
    for i, row in enumerate(grid):
        if i % 3 == 0 and i != 0:
            print(' ')
        print(f'{row[0:3]} {row[3:6]} {row[6:9]}')
    print('-' * 29)


if __name__ == '__main__':
    import copy
    input0 = [[0, 7, 9, 0, 6, 0, 0, 0, 5],
              [6, 0, 0, 0, 4, 0, 7, 0, 0],
              [3, 0, 0, 0, 9, 7, 0, 6, 0],
              [0, 0, 0, 0, 0, 0, 5, 0, 0],
              [5, 1, 7, 0, 0, 0, 3, 2, 6],
              [0, 0, 8, 0, 0, 0, 0, 0, 0],
              [0, 4, 0, 9, 7, 0, 0, 0, 3],
              [0, 0, 5, 0, 3, 0, 0, 0, 1],
              [2, 0, 0, 0, 1, 0, 4, 7, 0]]
    print_sudoku(input0)
    solvers = [('制約無し', solve_sudoku), ('対角数独', solve_sudoku_diagonal)]
    for name, solver in solvers:
        print(name)
        backtracks = 0
        input1 = copy.deepcopy(input0)
        if solver(input1):
            print_sudoku(input1)
        else:
            print('no solution')
        print(f'backtracks: {backtracks}回')

入出力結果(Terminal, cmd(コマンドプロンプト), Jupyter(IPython))

$ ./sample.py
-----------------------------
[0, 7, 9] [0, 6, 0] [0, 0, 5]
[6, 0, 0] [0, 4, 0] [7, 0, 0]
[3, 0, 0] [0, 9, 7] [0, 6, 0]
 
[0, 0, 0] [0, 0, 0] [5, 0, 0]
[5, 1, 7] [0, 0, 0] [3, 2, 6]
[0, 0, 8] [0, 0, 0] [0, 0, 0]
 
[0, 4, 0] [9, 7, 0] [0, 0, 3]
[0, 0, 5] [0, 3, 0] [0, 0, 1]
[2, 0, 0] [0, 1, 0] [4, 7, 0]
-----------------------------
制約無し
-----------------------------
[1, 7, 9] [2, 6, 3] [8, 4, 5]
[6, 5, 2] [1, 4, 8] [7, 3, 9]
[3, 8, 4] [5, 9, 7] [1, 6, 2]
 
[9, 3, 6] [7, 2, 1] [5, 8, 4]
[5, 1, 7] [4, 8, 9] [3, 2, 6]
[4, 2, 8] [3, 5, 6] [9, 1, 7]
 
[8, 4, 1] [9, 7, 2] [6, 5, 3]
[7, 6, 5] [8, 3, 4] [2, 9, 1]
[2, 9, 3] [6, 1, 5] [4, 7, 8]
-----------------------------
backtracks: 0回
対角数独
no solution
backtracks: 182回
$

上級問題でも解が見つかった制約無しの場合のバックトレースは0回だったから、人間が実際に解く難易度とコンピューターにとっての難易度は異なるみたい。

0 コメント:

コメントを投稿