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.
class Solution:
def validPos(self, board, row, col, c):
x = 3 * int(row / 3) # 3*3 start x index
y = 3 * int(col / 3) # 3*3 start y index
for i in range(9):
if board[row][i] == c:
return False
if board[i][col] == c:
return False
if board[x + int(i / 3)][y + i % 3] == c:
return False
return True
def solve(self, board, solved):
while solved != 81 and board[int(solved / 9)][solved % 9] != ".":
solved += 1
if solved is 81:
return True
i = int(solved / 9)
j = solved % 9
for c in "123456789":
if self.validPos(board, i, j, c):
board[i][j] = c
if self.solve(board, solved):
return True
else:
board[i][j] = "."
return False;
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
self.solve(board, 0)
以上是关于37. Sudoku Solver 数独求解的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 37. Sudoku Solver 求解数独