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 ‘.’.
1. 思路
题目意思就是给了一个数独盘,要求完成数独游戏,条件和上一题一样,行列都需要包含1-9,不重复
采用回溯法即可,满足条件往下走,不满足的情况回溯,
可以直接将36题的函数拿过来用,不过为了节省内存,进行一些改动
2.Code
class Solution:
def __init__(self):
self.board = None
def find_unassign(self):
for row in range(9):
for col in range(9):
if self.board[row][col] == '.':
return row, col
return -1, -1
# 验证行
def row_valid(self, row, cur):
for col in range(9):
if self.board[row][col] == cur:
return False
return True
# 验证列
def col_valid(self, col, cur):
for row in range(9):
if self.board[row][col] == cur:
return False
return True
# 验证3x3小方格
def cell_valid(self, row, col, cur):
for i in range(row, row + 3):
for j in range(col, col + 3):
if self.board[i][j] == cur:
return False
return True
# 判断当前填入的数是否满足
def cur_valid(self, row, col, cur):
start_row = row - row % 3
start_col = col - col % 3
if self.row_valid(row, cur) and self.col_valid(col, cur) and self.cell_valid(start_row, start_col, cur):
return True
return False
# 递归回溯
def solve(self):
row, col = self.find_unassign()
# 递归出口,完成数独
if row == -1 and col == -1:
return True
for num in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
if self.cur_valid(row, col, num):
self.board[row][col] = num
if self.solve():
return True
self.board[row][col] = '.'
return False
def solveSudoku(self, board):
self.board = board
self.solve()