我不明白为什么我对此没有解决办法? 有人可以为我找到正确的解决方法的正确方向吗?
当我尝试输入数字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
希望有人可以帮助我:)
答案 0 :(得分:0)
您确定这些计算正确吗?以procedure
为例,这将返回r=6
的{{1}},将row_start
添加到该索引将超出范围。请记住,您要检查给定框中的所有数字。
6
答案 1 :(得分:0)
我有要运行的代码,但是输出与预期不符。似乎可能缺少数独上的盒子,因为它只考虑行和列。谁能为我指出正确的方向,以使数独也为包装盒添加算法?如何在我的代码中实现呢?尝试了很多事情,但我被卡住了!