0.原题
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 93x3
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
.
1.代码
class Solution:
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
self.row = [[] for _ in range(9)]
self.column = [[] for _ in range(9)]
self.sub_box = [[[] for _ in range(3)]for _ in range(3)]
for i in range(9):
for j in range(9):
if board[i][j] != '.':
self.row[i].append(board[i][j])
self.column[j].append(board[i][j])
sub_box_row = i // 3
sub_box_column = j // 3
self.sub_box[sub_box_row][sub_box_column].append(board[i][j])
self.fun(board,0,0)
def fun(self,board,row,column):
if row == 9:
return True
else:
if board[row][column] == '.':
for i in ['1','2','3','4','5','6','7','8','9']:
sub_box_row = row // 3
sub_box_column = column // 3
if (i not in self.row[row]) and (i not in self.column[column]) and (i not in self.sub_box[sub_box_row][sub_box_column]):
board[row][column] = i
self.row[row].append(i)
self.column[column].append(i)
self.sub_box[sub_box_row][sub_box_column].append(i)
finish = self.next_square(board, row, column)
if finish:
return True
self.sub_box[sub_box_row][sub_box_column].pop()
self.column[column].pop()
self.row[row].pop()
board[row][column] = '.'
return False
else:
return(self.next_square(board,row,column))
def next_square(self,board,row=0,column=0):
if column == 8:
return(self.fun(board, row + 1, 0))
else:
return(self.fun(board, row, column + 1))
一开始没注意题目要求:rtype: void Do not return anything, modify board in-place instead.
结果查了很久的错,晕!
本题的思路与八皇后问题类似,仍然是使用递归遍历的思量,使用辅助数组进行剪枝操作。
八皇后问题请移步:https://blog.csdn.net/qq_17753903/article/details/82792082