力扣36题 数独
import time class Solution: def isValidSudoku(self, board): def isvalid(board, row, col, c): #操作是否合格 for i in range(9): if board[i][col] != '.' and board[i][col] == c: # row #判断这一行的数据 return False if board[row][i] != '.' and board[row][i] == c: # col #判断这一列的数据 return False if (board[3 * (row // 3) + i // 3][3 * (col // 3) + i // 3] != '.') and ( #判断每个小隔间的3*3 board[3 * (row // 3) + i // 3][3 * (col // 3) + i // 3] == c): return False return True if not board or len(board) <= 0: return #判空,board是否为空 for i in range(len(board)): #遍历行 for j in range(len(board[i])): #遍历列 if board[i][j] == '.': #如果该位置是空,则进入添加数据 for c in range(1,10): #遍历添加的数据1-9 if isvalid(board, i, j, str(c)): #判断是否合格 board[i][j] = str(c) #如果合格,则将其加入 if self.isValidSudoku(board): #递归调用 return True # else: board[i][j] = '.' #不符合就回溯添加‘.’ return False return True def printBoard(self,board): for i in range(len(board)): for j in range(len(board[i])): print(board[i][j],end=',') print() if __name__ == '__main__': time1 = time.time() board = [ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] solution = Solution() result =solution.isValidSudoku(board) solution.printBoard(board) time2 = time.time() print('run time:',time2-time1)