[LeetCode]题解(python):037-Sudoku Solver

时间:2023-03-09 07:29:46
[LeetCode]题解(python):037-Sudoku Solver

题目来源


https://leetcode.com/problems/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.


题意分析


Input:a unsolved Sudoku

Output: a solved Sudoku

Conditions:满足数独条件,只需要找到一个答案


题目思路

用dfs的思路,对每一个空进行1-9的选择,如果不满足则回溯;满足条件为isValid(),就是满足该行,该列以及该小九方格没有使用过两个一样的元素(即数字)


AC代码(Python)


 class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
def isValid(x, y):
temp = board[x][y]
board[x][y] = 'r'
for i in range(9):
if board[i][y] == temp:
return False
for i in range(9):
if board[x][i] == temp:
return False
for i in range(3):
for j in range(3):
if board[x / 3 * 3 + i][y / 3 * 3 + j] == temp:
return False
board[x][y] = temp
return True def dfs(board):
for i in range(9):
for j in range(9):
if board[i][j] == '.':
for k in '':
board[i][j] = k
if isValid(i,j) and dfs(board):
return True
board[i][j] = '.'
return False
return True dfs(board)