zoukankan      html  css  js  c++  java
  • 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)






  • 相关阅读:
    class和struct
    类内初始值(c++11)
    默认初始化、值初始化
    聚合类
    对象
    排序算法的比较
    快速排序
    堆排序
    ubunu设置java命令为全局的命令-添加到全局环境变量
    Mina笔记
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/8401769.html
Copyright © 2011-2022 走看看