如何在Python中实现可以解决奇/偶/素数独难题的约束满足问题?

问题描述

以下是完整的详细信息,请提供帮助。

实施约束满足问题,可以解决奇/偶/本数独难题。您必须定义约束,找到每个变量可能值的域,变量和非空域。定义约束后,使用回溯算法解决难题。请仔细阅读以下说明,以开发程序。

解决这个难题,玩家必须用一位数字(1到9)填充9x9网格。在81个单元中,有9个单元是绿色单元,它们的位置是固定的。剩余的72个单元格为灰色或白色。在游戏开始时,灰色和白色随机分配给单元。在行和列中有9个“正方形”(由3 x 3的空格组成)。每个3x3空间的中央必须有一个绿色单元格。每个行,列和正方形(每个9个空格)都需要填写,而在行,列或正方形内不重复任何数字。绿色单元格必须填充质数(2、3、5和7)。灰色单元格必须用奇数(1、3、5、7、9)填充,白色单元格必须用偶数(2、4、6、8)填充。在游戏开始时,必须用数字填充25%的随机位置。

提示:在3x3子空间中,4个单元格必须为灰色。中央单元格为绿色,其余4个单元格为白色。

注意:我仅在python中实现了简单的Sudoku拼图。

Python中的简单Sudoku Puzzle代码

    board = [
    [7,8,4,1,2,0],[6,7,5,9],[0,6,8],9,3,[9,5],2],[1,7]
]


def solve(bo):
    find = find_empty(bo)
    if not find:
        return True
    else:
        row,col = find

    for i in range(1,10):
        if valid(bo,i,(row,col)):
            bo[row][col] = i

            if solve(bo):
                return True

            bo[row][col] = 0

    return False


def valid(bo,num,pos):
    # Check row
    for i in range(len(bo[0])):
        if bo[pos[0]][i] == num and pos[1] != i:
            return False

    # Check column
    for i in range(len(bo)):
        if bo[i][pos[1]] == num and pos[0] != i:
            return False

    # Check Box
    Box_x = pos[1] // 3
    Box_y = pos[0] // 3

    for i in range(Box_y*3,Box_y*3 + 3):
        for j in range(Box_x * 3,Box_x*3 + 3):
            if bo[i][j] == num and (i,j) != pos:
                return False

    return True


def print_board(bo):
    for i in range(len(bo)):
        if i % 3 == 0 and i != 0:
            print("- - - - - - - - - - - - - ")

        for j in range(len(bo[0])):
            if j % 3 == 0 and j != 0:
                print(" | ",end="")

            if j == 8:
                print(bo[i][j])
            else:
                print(str(bo[i][j]) + " ",end="")


def find_empty(bo):
    for i in range(len(bo)):
        for j in range(len(bo[0])):
            if bo[i][j] == 0:
                return (i,j)  # row,col

    return None

print_board(board)
solve(board)
print("___________________")
print_board(board)

Output of above code

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)