标签:
题目来源:
https://leetcode.com/problems/sudoku-solver/
题意分析:
这次的题目就是上一题的进化版。填好一个数独。
题目思路:
这题直接用dfs暴力解决。把“*”用(1-9)直接填就行。时间复杂度比较高。要注意的是,题目要求没有返回值,所以要另外写一个函数用来判断填数之后是否满足可以填好。
代码(python):
1 class Solution(object): 2 def isValue(self,board,x,y): 3 #列符合 4 for i in range(9): 5 if i != x and board[i][y] == board[x][y]: 6 return False 7 for j in range(9): 8 if j != y and board[x][j] == board[x][y]: 9 return False 10 j += 1 11 m = 3*(x // 3);n = 3*(y // 3) 12 for i in range(3): 13 for j in range(3): 14 if (i + m != x or j + n != y) and board[i + m][j + n] == board[x][y]: 15 return False 16 return True 17 def dfs(self,board): 18 for i in range(9): 19 for j in range(9): 20 if board[i][j] == ‘.‘: 21 for k in ‘123456789‘: 22 board[i][j] = k 23 if self.isValue(board,i,j) and self.dfs(board): 24 return True 25 board[i][j] = ‘.‘ 26 return False 27 return True 28 29 def solveSudoku(self, board): 30 """ 31 :type board: List[List[str]] 32 :rtype: void Do not return anything, modify board in-place instead. 33 """ 34 self.dfs(board) 35
转载请注明出处:http://www.cnblogs.com/chruny/p/4926274.html
[LeetCode]题解(python):037-Sudoku Solver
标签:
原文地址:http://www.cnblogs.com/chruny/p/4926274.html