我正在尝试用 Python 解决 6x6 数独

问题描述 投票:0回答:1

我只是不明白为什么我没有找到解决方案? 有人可以指出我如何找到解决方案的正确方向吗?

当我尝试输入数字 1 - 6 时,它不起作用。只需打印“无解决方案”,因此它会跳过代码的解决方案部分。

非常感谢。

    SIZE = 6
# sudoku problem
# 0 is unknown cells
board = [
    [0, 6, 0, 0, 0, 0],
    [0, 0, 0, 6, 2, 4],
    [3, 0, 4, 0, 1, 0],
    [0, 0, 0, 2, 0, 0],
    [0, 0, 0, 4, 5, 0],
    [0, 0, 1, 0, 0, 2]]


# function to print sudoku
def print_sudoku():
    for i in board:
        print(i)


# Function to check if cells are unassigned and to add value to unassigned cells.
def unassigned_numbers(row, col):
    unassigned_num: int = 0
    for i in range(0, SIZE):
        for j in range(0, SIZE):
            # cell is unassigned
            if board[i][j] == 0:
                row = i
                col = j
                num_unassign = 1
                a = [row, col, num_unassign]
                return a
    a = [-1, -1, unassigned_num]
    return a


# function to check if a number can be assign a specific cell
def is_safe(n, r, c):
    # checking row
    for i in range(0, SIZE):
        # Cell has the same value
        if board[r][i] == n:
            return False
    # checking column
    for i in range(0, SIZE):
        # Cell has the same value
        if board[i][c] == n:
            return False
    row_start = (r // 2) * 3;
    col_start = (c // 3) * 2;
    # checking box
    for i in range(row_start, row_start + 3):
        for j in range(col_start, col_start + 2):
            if board[i][j] == n:
                return False
    return True


# Function to  check if we can put a value to a given cell
def solve_sudoku():
    row = 0
    col = 0
    # if all cells are assigned then the sudoku is already solved
    # pass by reference because number_unassigned will change the values of row and col
    a = unassigned_numbers(row, col)
    if a[2] == 0:
        return True
    row = a[0]
    col = a[1]
    # number between 1 to 6
    for i in range(1, 7):
        if is_safe(i, row, col):
            board[row][col] = i
            # backtracking
            if solve_sudoku():
                return True
            # if the solution don't work reassign the cell
            board[row][col] = 0
    return False


if solve_sudoku():
    print_sudoku()
else:
    print("No solution")

这里可能出现什么问题? 我猜可能是在这一部分:

检查栏

    for i in range(0, SIZE):
        # Cell has the same value
        if board[i][c] == n:
            return False
    row_start = (r // 2) * 3;
    col_start = (c // 3) * 2;
    # checking box
    for i in range(row_start, row_start + 3):
        for j in range(col_start, col_start + 2):
            if board[i][j] == n:
                return False
    return True

希望有人能帮助我:)

python sudoku
1个回答
0
投票

您确定这些计算正确吗?以

r=6
为例,这将返回
row_start
6
,将
3
添加到该索引将超出范围。请记住,您要检查给定框中的所有数字。

(r // 2) * 2
r -> row_start
1 -> 0 
2 -> 2 
3 -> 2
4 -> 4
5 -> 4
6 -> 6

(c // 3) * 2
c -> col_start
1 -> 0
2 -> 0
3 -> 2
4 -> 2
5 -> 2
6 -> 4
© www.soinside.com 2019 - 2024. All rights reserved.