本文目錄一覽:
數獨人造解法的一些技巧及其python實現怎麼解決
總共有十幾種解題技巧,其中最直接的是顯式唯一數法和隱式唯一數法。所謂顯式唯一數法,是指某個格只有一個候選數可選,這個格自然就只能填這個候選數了。
而隱式唯一數法的意思則是,某一行、列或宮只有一個位置可以填某個候選數,當然,這個位置肯定就填這個候選數了。
怎麼用python解數獨的算法題,給個矩陣裡面填充了若干數,用程序自動給填充完整
class Solution:
# @param board, a 9×9 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)
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/242790.html