def __init__(self, squares): """Squares is a nested list representing an initial sudoku board. A 0 represents an empty square, while a nonzero digit represents a square filled with that value.""" self.dlxrows = squares_to_dlx_rows(squares) sparseMatrix = SparseMatrix(self.dlxrows) self.dlx = DLX(sparseMatrix)
def testChooseColumn(self): matrix = SparseMatrix(rows1) dlx = DLX(matrix) coltable = matrix.column_table column = dlx.choose_column() assert coltable[0] == column matrix.cover(column) # See Figure 3; column D now only has one node in it. after_cover = dlx.choose_column() assert coltable[3] == after_cover
class SudokuPuzzle(object): """Representation of a Sudoku puzzle, with methods to convert back and forth from an instance of DLX.""" def __init__(self, squares): """Squares is a nested list representing an initial sudoku board. A 0 represents an empty square, while a nonzero digit represents a square filled with that value.""" self.dlxrows = squares_to_dlx_rows(squares) sparseMatrix = SparseMatrix(self.dlxrows) self.dlx = DLX(sparseMatrix) def solve(self): """Solve the sudoku puzzle. Return value is a nested list in the same format as the input to the constructor.""" self.dlx_soln = self.dlx.search() if self.dlx_soln: self.soln_rows = [node.rowindex for node in self.dlx_soln if node] else: return None dlx_encoded_soln = [self.dlxrows[row] for row in self.soln_rows] rcvs = map(dlx_row_to_rcv, dlx_encoded_soln) out = build_blank_board() for row, col, val in rcvs: out[row][col] = val return out
class SudokuPuzzle(object): """Representation of a Sudoku puzzle, with methods to convert back and forth from an instance of DLX.""" def __init__(self, squares): """Squares is a nested list representing an initial sudoku board. A 0 represents an empty square, while a nonzero digit represents a square filled with that value.""" self.dlxrows = squares_to_dlx_rows(squares) sparseMatrix = SparseMatrix(self.dlxrows) self.dlx = DLX(sparseMatrix) def solve(self): """Solve the sudoku puzzle. Return value is a nested list in the same format as the input to the constructor.""" self.dlx_soln = self.dlx.search() if self.dlx_soln: self.soln_rows = [node.rowindex for node in self.dlx_soln if node] else: return None dlx_encoded_soln = [self.dlxrows[row] for row in self.soln_rows] rcvs = map(dlx_row_to_rcv, dlx_encoded_soln) out = build_blank_board() for row,col,val in rcvs: out[row][col] = val return out
def testSearch(self): matrix = SparseMatrix(rows1) dlx = DLX(matrix) result = dlx.search() assert result mat2 = SparseMatrix(rows2) dlx2 = DLX(mat2) result2 = dlx2.search() assert not result2 mat3 = SparseMatrix(rows3) dlx3 = DLX(mat3) res3 = dlx3.search() assert res3 mat4 = SparseMatrix(rows4) dlx4 = DLX(mat4) res4 = dlx4.search() assert res4