题目:
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...
...and its solution numbers marked in red.
python解法一:
思路:采用深度优先算法,每填入一个数字都判断该数字是否是合法的。由于之前填入的数字都已判断过,所以不需要进行冗余的判断整个数组是否是合法的。
class Solution:
def isValidSudoku(self, board, i, j):
for m in range(len(board[i])):
if m!=j and board[i][j]==board[i][m]:
return False
for n in range(len(board)):
if n!=i and board[i][j]==board[n][j]:
return False
for m in range(i//3*3,i//3*3+3):
for n in range(j//3*3,j//3*3+3):
if (m!=i and n!=j) and board[i][j]==board[m][n]:
return False
return True
def solveSudokuDFS(self, board, i, j):
if i==9:
return True
if j>=9:
return self.solveSudokuDFS(board,i+1,0)
if board[i][j]==".":
for k in ["1","2","3","4","5","6","7","8","9"]:
board[i][j] = k
if self.isValidSudoku(board,i,j):
if self.solveSudokuDFS(board,i,j+1):
return True
board[i][j] = "."
else :
return self.solveSudokuDFS(board,i,j+1)
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
self.solveSudokuDFS(board, 0, 0)