37. Sudoku Solver 数独求解

Posted Long Long Journey

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了37. Sudoku Solver 数独求解相关的知识,希望对你有一定的参考价值。

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character \'.\'.

You may assume that there will be only one unique solution.


A sudoku puzzle...


...and its solution numbers marked in red.


  1. class Solution:
  2. def validPos(self, board, row, col, c):
  3. x = 3 * int(row / 3) # 3*3 start x index
  4. y = 3 * int(col / 3) # 3*3 start y index
  5. for i in range(9):
  6. if board[row][i] == c:
  7. return False
  8. if board[i][col] == c:
  9. return False
  10. if board[x + int(i / 3)][y + i % 3] == c:
  11. return False
  12. return True
  13. def solve(self, board, solved):
  14. while solved != 81 and board[int(solved / 9)][solved % 9] != ".":
  15. solved += 1
  16. if solved is 81:
  17. return True
  18. i = int(solved / 9)
  19. j = solved % 9
  20. for c in "123456789":
  21. if self.validPos(board, i, j, c):
  22. board[i][j] = c
  23. if self.solve(board, solved):
  24. return True
  25. else:
  26. board[i][j] = "."
  27. return False;
  28. def solveSudoku(self, board):
  29. """
  30. :type board: List[List[str]]
  31. :rtype: void Do not return anything, modify board in-place instead.
  32. """
  33. self.solve(board, 0)






以上是关于37. Sudoku Solver 数独求解的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 37. Sudoku Solver 求解数独

LeetCode37. Sudoku Solver

36. Valid Sudoku/37. Sudoku Solver - 数独问题-- backtracking 经典

37. Sudoku Solver

我的数独求解器哪里出了问题?

37. Sudoku Solver