Not elegant at all, but readable sudoku solver.
https://leetcode.com/problems/sudoku-solver/
class Solution(object):
def checkNew(self, i,j,k,board):
for jj in range(9):
if board[i][jj] == str(k):
return False
for ii in range(9):
if board[ii][j] == str(k):
return False
iB = i//3
jB = j//3
b = []
for ii in range(3):
for jj in range(3):
if board[3*iB+ii][3*jB+jj] == str(k):
return False
return True
def backtrack(self, board):
# Find a blank element. The search direction does not a matter,
# but row-oriented here.
for i in range(9):
for j in range(9):
if board[i][j] == ".":
# If blank, try numbers from 1 to 9
for k in range(9):
if self.checkNew(i,j,k+1,board): # Check if k is OK
board[i][j]=str(k+1)
if self.backtrack(board): # Try next blank until OK
return True
else:
board[i][j] = "." # if inconsistent, step back
else:
return False
return True
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
self.backtrack(board)
0 件のコメント:
コメントを投稿