#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
37:sudoku Solver
https://oj.leetcode.com/problems/sudoku-solver/
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells is indicated by the character '.
Assume that there would be is only one unique solution.
===comments by dabay===
Progressive scan, when encountering "." , try every possible valid_num.
If you can DFS to the end, return True; otherwise, reset this position to "." For the next attempt.
‘‘‘
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):
def next_position (position):
I, j = position
J + = 1
If J >= 9:
J-= 9
i + = 1
Return (I, J)
def valid_nums (board, position):
I, j = position
s = [STR (n) for N in xrange (1, 10)]
For row in xrange (9):
If BOARD[ROW][J]! = '. ' and Board[row][j] in s:
S.remove (Board[row][j])
For Col in Xrange (9):
If BOARD[I][COL]! = '. ' and Board[i][col] in s:
S.remove (Board[i][col])
II = I/3
JJ = J/3
For row in Xrange (3):
For Col in Xrange (3):
If BOARD[II*3+ROW][JJ*3+COL]! = '. ' and Board[ii*3+row][jj*3+col] in s:
S.remove (Board[ii*3+row][jj*3+col])
return s
def solveSudoku2 (board, position):
I, j = position
if i = = 9:
Return True
If board[i][j] = = '. ':
Nums = valid_nums (board, position)
For N in Nums:
BOARD[I][J] = n
If SOLVESUDOKU2 (board, next_position (position)) is True:
Return True
BOARD[I][J] = '. '
Else
Return SOLVESUDOKU2 (board, next_position (position))
SOLVESUDOKU2 (board, (0, 0))
def print_board (board):
Print "-" * 30
For row in board:
For x in row:
Print "%s"% x,
Print
Print "-" * 30
def main ():
s = solution ()
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"]
]
Print_board (board)
S.solvesudoku (board)
Print_board (board)
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]37:sudoku Solver