跳到主要内容

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

分析

无。

代码

# Sudoku Solver
# Time complexity O(9^4), Space complexity O(1)
class Solution:
def solveSudoku(self, board):
self._solveSudoku(board)

def _solveSudoku(self, board):
for i in range(9):
for j in range(9):
if board[i][j] == '.':
for k in range(9):
board[i][j] = str(k + 1)
if self.isValid(board, i, j) and self._solveSudoku(board):
return True
board[i][j] = '.'
return False
return True

# Check if (x, y) is valid
def isValid(self, board, x, y):
# Check y column
for i in range(9):
if i != x and board[i][y] == board[x][y]:
return False
# Check x row
for j in range(9):
if j != y and board[x][j] == board[x][y]:
return False
for i in range(3 * (x // 3), 3 * (x // 3 + 1)):
for j in range(3 * (y // 3), 3 * (y // 3 + 1)):
if (i != x or j != y) and board[i][j] == board[x][y]:
return False
return True

相关题目