Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
- Each of the digits 1-9 must occur exactly once in each row.
- Each of the digits 1-9 must occur exactly once in each column.
- Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
Empty cells are indicated by the character '.'.
A sudoku puzzle...
...and its solution numbers marked in red.
Note:
- The given board contain only digits 1-9 and the character '.'.
- You may assume that the given Sudoku puzzle will have a single unique solution.
- The given board size is always 9x9.
我的代码如下:
def checks(board):
seen = []
for i, row in enumerate(board):
for j, c in enumerate(row):
if c != '.':
seen += [(c,j),(i,c),(i/3,j/3,c)]
return len(seen) == len(set(seen))
board=[["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
cboard=[[board[j] for i in range(9)] for j in range(9)]
f=[]
for i in range(9):
for j in range(9):
if cboard[j]=='.':
f+=[[i,j]]
for m in f:
h=[]
i,j=m
cboard[j]='123456789'
for b in range((i//3)*3,(i//3+1)*3):
for v in range((j//3)*3,(j//3+1)*3):
if [b,v] not in f:
h.append(board[v])
for b in range(9):
if [b,j] not in f:
h.append(board[j])
for v in range(9):
if [i,v] not in f:
h.append(board[v])
for x in list(set(h)):
cboard[j]=cboard[j].replace(x,'')
f=[]
for i in range(9):
for j in range(9):
if len(cboard[j])>1:
f+=[[i,j]]
l=[]
def final(f):
if len(f)==0:
l.append(1)
return
if len(f)>0:
i,j=f[0]
for x in cboard[j]:
board[j]=x
if checks(board):
print(board)
print('')
final(f[1:])
if len(l) !=0:
break
if not checks(board):
board[j]='.'
return
if len(l) !=0:
return
final(f)