我正在尝试用Python制作一个数独解算器
其思想是针对每个值,如果其0表示为空,则在正方形、x和y行中查找数字
然后在范围(1,10)中应用for循环,如果该值不在找到的数字列表中,则将该值更改为0
但是,程序会跳过一些空白值
例如:
[[8, 1, 0, 0, 3, 0, 0, 2, 7],
[0, 6, 2, 0, 5, 0, 0, 9, 0],
[0, 7, 0, 0, 0, 0, 0, 0, 0],
[0, 9, 0, 6, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 2, 0, 0, 0, 4],
[0, 0, 8, 0, 0, 5, 0, 7, 0],
[0, 0, 0, 0, 0, 0, 0, 8, 0],
[0, 2, 0, 0, 1, 0, 7, 5, 0],
[3, 8, 0, 0, 7, 0, 0, 4, 2]]
此输入提供以下信息:
[8, 1, 4, 9, 3, 6, 5, 2, 7]
[0, 6, 2, 1, 5, 4, 3, 9, 8]
[5, 7, 3, 2, 8, 0, 4, 1, 6]
[2, 9, 5, 6, 4, 3, 1, 0, 0]
[1, 3, 6, 7, 2, 8, 9, 0, 4]
[4, 0, 8, 0, 9, 5, 2, 7, 3]
[6, 4, 1, 3, 0, 2, 0, 8, 9]
[9, 2, 0, 4, 1, 0, 7, 5, 0]
[3, 8, 0, 5, 7, 9, 6, 4, 2]
我不明白原因。我的代码在这里:
class Sudoku:
sudoku = [[8, 1, 0, 0, 3, 0, 0, 2, 7],
[0, 6, 2, 0, 5, 0, 0, 9, 0],
[0, 7, 0, 0, 0, 0, 0, 0, 0],
[0, 9, 0, 6, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 2, 0, 0, 0, 4],
[0, 0, 8, 0, 0, 5, 0, 7, 0],
[0, 0, 0, 0, 0, 0, 0, 8, 0],
[0, 2, 0, 0, 1, 0, 7, 5, 0],
[3, 8, 0, 0, 7, 0, 0, 4, 2]]
def find_square(self,line_x,line_y):
square_list = []
if line_y <= 2:
line_y = 0
if line_y > 2 and line_y <= 5:
line_y = 3
if line_y > 5:
line_y = 6
if line_x <= 2:
line_x = 0
if line_x > 2 and line_x <= 5:
line_x = 3
if line_x > 5:
line_x = 6
for i in range(0,3):
for j in range(0,3):
list = self.sudoku[line_y + i]
if list[line_x + j] != 0:
square_list.append(list[line_x + j])
return square_list
def find_x(self,line_x):
temperory_list = []
for line in self.sudoku:
if line[line_x] != 0:
temperory_list.append(line[line_x])
return temperory_list
def find_y(self,line_y):
temperory_list = []
for i in self.sudoku[line_y]:
if i != 0:
temperory_list.append(i)
return temperory_list
def take_numbers(self,line_x,line_y):
temperory_list = []
list = []
for i in self.find_square(line_x,line_y):
temperory_list.append(i)
for i in self.find_x(line_x):
temperory_list.append(i)
for i in self.find_y(line_y):
temperory_list.append(i)
for i in temperory_list:
if i not in list:
list.append(i)
return list
def solve(self):
for y in range(9):
for x in range(9):
if self.sudoku[y][x] == 0:
list = self.take_numbers(x,y)
for i in range(1,10):
if i not in list:
self.sudoku[y][x] = i
break
def print_sudoku(self):
for i in self.sudoku:
print(i)
test = Sudoku()
test.solve()
test.print_sudoku()
目前没有回答
相关问题 更多 >
编程相关推荐