题目如下:
解题思路:也没啥好说的,回溯法。
代码如下:
class Solution(object): length = 9 def isValid(self,row,column,val,grid): #check row,column for i in range(self.length): if val == grid[row][i] and i != column: return False if val == grid[i][column] and i != row: return False #check self grid r = (row - row % 3) c = (column - column%3) for i in range(r,r+3): for j in range(c,c+3): if grid[i][j] == val and i != row and j != column: return False return True def getValid(self,x,y,grid): if grid[x][y] == str(self.length): return -1 elif grid[x][y] == '.': start = 1 else: start = int(grid[x][y]) + 1 for i in range(start,self.length+1): if self.isValid(x,y,str(i),grid) == True: return i return -1 def getNextInx(self,i,j): if j < self.length-1: j += 1 else: i += 1 j = 0 return i,j def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ stack = [] i = j = 0 while i < self.length: while j < self.length and i < self.length: if board[i][j] != '.': i,j = self.getNextInx(i,j) continue while True: #print board[0] flag = False v = self.getValid(i,j,board) if v != -1: board[i][j] = str(v) stack.append((i, j)) flag = True if flag == False: while len(stack) > 0: x,y = stack[-1] v = self.getValid(x,y,board) if v != -1: board[x][y] = str(v) flag = True i = x j = y break else: board[x][y] = '.' del stack[-1] ## if flag still false,invalid sudoku if flag == False: return break else: break i, j = self.getNextInx(i, j)