Description
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…
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.
Submissions
这道题的解题思路可以利用上一题的方法,使用双循环找到值为’.‘的位置循环填入1-9,判断如果填入前与填入后都成立则标记为True,否则还置为’.’。
实现代码如下:
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def isValid(x,y):
tmp=board[x][y]; board[x][y]=''
for i in range(9):
if board[i][y]==tmp: return False
for i in range(9):
if board[x][i]==tmp: return False
for i in range(3):
for j in range(3):
if board[int(x/3)*3+i][int(y/3)*3+j]==tmp: return False
board[x][y]=tmp
return True
def dfs(board):
for i in range(9):
for j in range(9):
if board[i][j]=='.':
for k in '123456789':
board[i][j]=k
if isValid(i,j) and dfs(board):
return True
board[i][j]='.'
return False
return True
dfs(board)