本文目录一览:
数独人造解法的一些技巧及其python实现怎么解决
总共有十几种解题技巧,其中最直接的是显式唯一数法和隐式唯一数法。所谓显式唯一数法,是指某个格只有一个候选数可选,这个格自然就只能填这个候选数了。
而隐式唯一数法的意思则是,某一行、列或宫只有一个位置可以填某个候选数,当然,这个位置肯定就填这个候选数了。
怎么用python解数独的算法题,给个矩阵里面填充了若干数,用程序自动给填充完整
class Solution:
# @param board, a 9x9 2D array
# Solve the Sudoku by modifying the input board in-place.
# Do not return any value.
def solveSudoku(self, board):
self.board = board
self.solve()
def findUnassigned(self):
for row in range(9):
for col in range(9):
if self.board[row][col] == ".":
return row, col
return -1, -1
def solve(self):
row, col = self.findUnassigned()
#no unassigned position is found, puzzle solved
if row == -1 and col == -1:
return True
for num in ["1","2","3","4","5","6","7","8","9"]:
if self.isSafe(row, col, num):
self.board[row][col] = num
if self.solve():
return True
self.board[row][col] = "."
return False
def isSafe(self, row, col, ch):
boxrow = row - row%3
boxcol = col - col%3
if self.checkrow(row,ch) and self.checkcol(col,ch) and self.checksquare(boxrow, boxcol, ch):
return True
return False
def checkrow(self, row, ch):
for col in range(9):
if self.board[row][col] == ch:
return False
return True
def checkcol(self, col, ch):
for row in range(9):
if self.board[row][col] == ch:
return False
return True
def checksquare(self, row, col, ch):
for r in range(row, row+3):
for c in range(col, col+3):
if self.board[r][c] == ch:
return False
return True
用Python判断数独是否正确
#coding=utf-8
num_list=[
[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]
]
tmp = [1,2,3,4,5,6,7,8,9]
def check_shudu(num_list):
#
if len(num_list)9:
return -1
#
for j in num_list:
if sorted(j)tmp:
return -1
#
for i in range(9):
if sorted([j[i] for j in num_list])tmp:
return -1
#
for n in range(3):
for k in range(3):
jiu = []
for i in range(n*3,n*3+3):
for j in range(k*3,k*3+3):
jiu.append(num_list[i][j])
if sorted(jiu)tmp:
return -1
return 1
print check_shudu(num_list)