Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'
.
You may assume that there will be only one unique solution.
A sudoku puzzle...
NP问题~处理方法都是类似得~ 循环处理子问题,对于每个格子,带入不同的9个数,然后判合法,如果成立就递归继续,结束后把数字设回空~注意helper函数里得boolean返回值~
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):
if board is None or len(board) != 9 or len(board[0]) != 9:
return None
self.helper(board, 0, 0)
def helper(self, board, i, j):
if j >= 9:
return self.helper(board, i + 1, 0)
if i == 9:
return True
if board[i][j] == '.':
for k in xrange(1, 10):
board[i][j] = str(k)
if self.isValid(board, i, j):
if self.helper(board, i, j + 1):
return True
board[i][j] = '.'
else:
return self.helper(board, i, j + 1)
return False
def isValid(self, board, i, j):
for m in xrange(9):
if m != j and board[i][m] == board[i][j]:
return False
for n in xrange(9):
if n != i and board[n][j] == board[i][j]:
return False
for m in xrange(i / 3 * 3, i / 3 * 3 + 3):
for n in xrange(j / 3 * 3, j / 3 * 3 + 3):
if m != i and n != j and board[m][n] == board[i][j]:
return False
return True