这题难度为困难,目前通过率为32.2%
题目:
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
1.Each of the digits 1-9 must occur exactly once in each row.
2.Each of the digits 1-9 must occur exactly once in each column.
3.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 ‘.’.
Note:
1.The given board contain only digits 1-9 and the character '.'.
2.You may assume that the given Sudoku puzzle will have a single unique solution.
3.The given board size is always 9x9.
题目是给出一个未填完的数独,需要用程序填满。
思路:
下面的代码主要使用了回溯法,当一个格子9次填数字都失败的时候,则返回上一个填的格子,试填下一个数字,直到9*9个格子全部填完。
判断方法仍然是三个数组,分别对应行、列和每个九宫格,当要填的数字与规则不冲突的时候,才能填进去并递归。
代码:
class Solution:
def solveSudoku(self, board):
self.board = board
self.row = [[False for i in range(9)] for j in range(9)]
self.col = [[False for i in range(9)] for j in range(9)]
self.sqr = [[[False for i in range(9)] for j in range(3)] for k in range(3)]
self.judge = False
for i in range(9):
for j in range(9):
if self.board[i][j] != '.':
num = int(self.board[i][j]) - 1
self.row[i][num] = True
self.col[j][num] = True
self.sqr[i // 3][j // 3][num] = True
self.solve(0,0)
def solve(self,i,j):
if i == 9:
self.judge = True
return
if self.board[i][j] == '.':
for k in range(9):
if not(self.row[i][k] or self.col[j][k] or self.sqr[i//3][j//3][k]):
self.row[i][k] = True
self.col[j][k] = True
self.sqr[i // 3][j // 3][k] = True
self.board[i][j]=str(k+1)
if j==8 :
self.solve(i+1,0)
else:
self.solve(i,j+1)
if not self.judge:
self.row[i][k] = False
self.col[j][k] = False
self.sqr[i//3][j//3][k] = False
self.board[i][j] = "."
else:
return
else:
if j == 8:
self.solve(i + 1, 0)
else:
self.solve(i, j + 1)
return
复杂度分析:
由于使用了回溯法,因此难以判断算法复杂度。
提交: