问题:给定一个9*9的二维数组,数组元素为1~9的字符串,“.”代表该位置为空,将“.”替换为1~9的字符串,使数组中的数据满足数独的规则
示例:
解决思路:先进行一次9*9的遍历,统计已有的数据,再进行遍历,如果该位置为空,则循环 使用1~9中的字符串进行填充,递归的填充后面的空位,如果某个位置不能正确填充,说明前面的填充有误,则前面的填充需要重新选择
Python代码:
class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: None Do not return anything, modify board in-place instead. """ row = {i:{str(j):0 for j in range(1,10)} for i in range(9)} col = {i:{str(j):0 for j in range(1,10)} for i in range(9)} part = {m:{j:{str(i):0 for i in range(1,10)} for j in range(3)} for m in range(3)} for i in range(9): for j in range(9): ele = board[i][j] if ele != ".": row[i][ele] += 1 col[j][ele] += 1 part[i//3][j//3][ele] += 1 self.solve(board,row,col,part) def solve(self,board,row,col,part,start_row=0): for i in range(start_row,9): for j in range(9): if board[i][j] == ".": for m in "123456789": if row[i][m] + col[j][m] + part[i//3][j//3][m] == 0: board[i][j] = m row[i][m] += 1 col[j][m] += 1 part[i//3][j//3][m] += 1 if self.solve(board,row,col,part,i): return True board[i][j] = "." row[i][m] -= 1 col[j][m] -= 1 part[i//3][j//3][m] -= 1 return False return True