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)






posted @ 2018-02-01 23:28  xiejunzhao  阅读(153)  评论(0编辑  收藏  举报