码迷,mamicode.com
首页 > 其他好文 > 详细

37. Sudoku Solver 数独求解

时间:2018-02-02 00:52:24      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:har   bubuko   ica   size   rip   oar   image   char   return   

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 数独求解

标签:har   bubuko   ica   size   rip   oar   image   char   return   

原文地址:https://www.cnblogs.com/xiejunzhao/p/8401769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!