def solve_bttn_func(self): self.label.setText("") su = Sudoku(self.translate_to_2d()) not_defined = su.get_not_defined() su.solve() for ye, (y, y_i) in enumerate(zip(su.sudoku, self.elements)): for xe, (x, x_i) in enumerate(zip(y, y_i)): if not x: self.label.setText("There is no solution - Invalid sudoku") return x_i.setText(str(x)) if (xe, ye) in not_defined: x_i.setStyleSheet("background-color:lightblue")
def tipp_bttn_func(self): self.label.setText("") su = Sudoku(self.translate_to_2d()) if not su.is_solved(): not_defined = su.get_not_defined() solution = su.solve() x, y = random.choice(not_defined) self.elements[y][x].setText(str(solution[y][x])) self.elements[y][x].setStyleSheet("background-color:lightgreen")
def run(): for method in methods: stats.append([]) for j, level in enumerate(levels): stats[method].append([]) sub_dir = benchmark_dir + '/' + level puzzle_list = os.listdir(sub_dir) puzzle_list = sorted([name for name in puzzle_list if 'in' in name.lower()]) for puzzle in puzzle_list: puzzle_dir = sub_dir + '/' + puzzle with open(puzzle_dir) as f: grid = parse_input(f) game = Sudoku(grid, method) solution, steps, runtime = game.solve() stats[method][j].append((puzzle, steps, runtime)) assert solution != None print(puzzle, methods_name[method],'Steps:', steps, 'time(s):',runtime) print() print('bt: backtracking') print('cp1: one-candidate') print('cp2: cp1+naked-pair+hidden-pair') print('cp3: cp1+cp2+x-wing') print('mrv: Minimum Remaining Values') print() print('Average backtracking steps and runtime:') print('tuples are in the format of (steps, time in milliseconds)') print('puzzle_level, bt, bt+cp1, bt+cp2, bt+cp3, bt+cp3+mrv') for j, level in enumerate(levels): stat = [] for method in methods: time = 0 step = 0 count = len(stats[method][j]) for p in stats[method][j]: time += p[2] step += p[1] stat.append('({}, {:.2f})'.format(step // count, time * 1000 / count)) print(level + ',' + ','.join(stat)) print(comment)
from sudoku_solver import Sudoku solved = 0 result = 0 with open('p096_sudoku.txt', 'r') as f: line = f.readline() while line.startswith('Grid'): print(line.strip()) matrix = [[int(ch) for ch in f.readline().strip()] for i in range(9)] sudoku = Sudoku(matrix) sudoku.solve() if sudoku.unsolved_cells == 0: solved += 1 result += (sudoku.cells[0][0].value * 100 + sudoku.cells[0][1].value * 10 + sudoku.cells[0][2].value) print(sudoku) line = f.readline() print(f'Решено {solved} судоку из 50') print(f'Ответ: {result}')
class SudokuUI: BOARD_SIZE = 9 def __init__(self, size, matrix): self._size_x = size # window size self._size_y = self._size_x self._block_size = self._size_x / 9 # cell self.sudoku_solver = Sudoku(matrix) pg.init() pg.display.set_caption("Sudoku Solver") self._window = pg.display.set_mode((self._size_x, self._size_y), RESIZABLE) self._window.fill(WHITE) self.prepare_board() self.clicked = None self.key = None self.delete = False self.simulate = False def clear_window(self): self._window.fill(WHITE) def clear_cell(self, y, x): cell_rect = pg.Rect(x * self._block_size + self._block_size * 0.1, y * self._block_size + self._block_size * 0.1, self._block_size * 0.8, self._block_size * 0.8) self._window.fill(WHITE, cell_rect) def draw(self, x, y, color=BLUE): font = pg.font.Font('freesansbold.ttf', int(self._block_size * 0.6)) submatrix_rect = pg.Rect(x * (self._block_size * 3), y * (self._block_size * 3), self._block_size * 3, self._block_size * 3) pg.draw.rect(self._window, BLACK, submatrix_rect, int(self._block_size / 10)) cell_rect = pg.Rect(x * self._block_size, y * self._block_size, self._block_size, self._block_size) pg.draw.rect(self._window, (0, 0, 0), cell_rect, 1) val = self.sudoku_solver.get_cell(x, y) val = val if val != '.' else '' #print('color:', color, 'x:', x, 'y:', y, 'val:', val) text = font.render(val, True, color) textRect = text.get_rect() textRect.center = (self._block_size / 2 + (self._block_size * y), self._block_size / 2 + (self._block_size * x)) self._window.blit(text, textRect) pg.display.update() def prepare_board(self): for x in range(self.BOARD_SIZE): for y in range(self.BOARD_SIZE): self.draw(x, y) pg.display.update() def click(self, pos): if pos[0] < self._size_x and pos[1] < self._size_y: x = pos[0] // self._block_size y = pos[1] // self._block_size return (int(y), int(x)) def solve(self): return self.sudoku_solver.solve() def revert(self, matrix): self.sudoku_solver.reset_board(matrix) def make_backup(self): return self.sudoku_solver.make_backup() def place(self, x, y, num): self.sudoku_solver.place_cell(x, y, num) def remove(self, x, y): self.sudoku_solver.remove_cell(x, y) def play(self): run = True while run: for event in pg.event.get(): if event.type == pg.QUIT: run = False if event.type == pg.MOUSEBUTTONDOWN: pos = pg.mouse.get_pos() self.clicked = self.click(pos) else: self.clicked = False if event.type == pg.KEYDOWN: keys = pg.key.get_pressed() if keys[pg.K_1] or keys[pg.K_KP1]: self.key = '1' if keys[pg.K_2] or keys[pg.K_KP2]: self.key = '2' if keys[pg.K_3] or keys[pg.K_KP3]: self.key = '3' if keys[pg.K_4] or keys[pg.K_KP4]: self.key = '4' if keys[pg.K_5] or keys[pg.K_KP5]: self.key = '5' if keys[pg.K_6] or keys[pg.K_KP6]: self.key = '6' if keys[pg.K_7] or keys[pg.K_KP7]: self.key = '7' if keys[pg.K_8] or keys[pg.K_KP8]: self.key = '8' if keys[pg.K_9] or keys[pg.K_KP9]: self.key = '9' if keys[pg.K_SPACE]: self.simulate = True else: self.simulate = False if keys[pg.K_DELETE] or keys[pg.K_BACKSPACE] or keys[ pg.K_d]: self.delete = True else: self.delete = False if self.simulate: print('\nTrying to solve....') current_matrix = self.make_backup() can_solve = self.solve() #print('Can solve:', can_solve) if not can_solve: self.revert(current_matrix) print( '\nThe position cannot be solved. Remove elements from arbitrary cells and try again.' ) else: self.clear_window() self.prepare_board() pg.display.update() run = False self.simulate = False pg.display.update() if self.delete: if self.clicked: #print('val before removing:', self.sudoku_solver.get_cell(self.clicked[0],self.clicked[1])) self.remove(self.clicked[0], self.clicked[1]) #print('val after removing:', self.sudoku_solver.get_cell(self.clicked[0],self.clicked[1])) self.clear_cell(self.clicked[0], self.clicked[1]) self.draw(self.clicked[0], self.clicked[1]) self.delete = False #[print(row) for row in self.sudoku_solver._matrix] pg.display.update() if self.key: if self.clicked: #print('self.clicked:', self.clicked, 'self.key:', self.key) is_valid_placement = self.sudoku_solver.is_valid( self.clicked[0], self.clicked[1], self.key) self.clear_cell(self.clicked[0], self.clicked[1]) self.place(self.clicked[0], self.clicked[1], self.key) self.draw(self.clicked[0], self.clicked[1]) pg.display.update() if not is_valid_placement: self.clear_cell(self.clicked[0], self.clicked[1]) self.draw(self.clicked[0], self.clicked[1], RED) pg.display.update() self.delete = True print( f"\nThe placement of {self.key} on ({self.clicked[0]},{self.clicked[1]}) is invalid. Please remove current element and try something else" ) #[print(row) for row in self.sudoku_solver._matrix] else: current_matrix = self.make_backup() can_solve = self.solve() #print('Can solve:', can_solve) self.revert(current_matrix) if not can_solve: self.clear_cell(self.clicked[0], self.clicked[1]) self.draw(self.clicked[0], self.clicked[1], RED) pg.display.update() self.delete = True print( '\nThe cell is valid, BUT the position CANNOT be solved from here. Please remove current element and try something else' ) #[print(row) for row in self.sudoku_solver._matrix] else: if self.sudoku_solver.is_full(): print("\nWOW, you've solved it!") run = False else: print( '\nThe cell is valid AND you CAN solve from here on. Good job!' ) self.clicked = False self.key = None pg.display.update()
def solve_sudoku(matrix): sudoku_solver = Sudoku(matrix) is_solved = sudoku_solver.solve("A", "0", time.time(), False) return sudoku_solver.grid if is_solved else None
from sudoku_solver import Sudoku example = Sudoku([[9, 0, 6, 0, 7, 0, 4, 0, 3], [0, 0, 0, 4, 0, 0, 2, 0, 0], [0, 7, 0, 0, 2, 3, 0, 1, 0], [5, 0, 0, 0, 0, 0, 1, 0, 0], [0, 4, 0, 2, 0, 8, 0, 6, 0], [0, 0, 3, 0, 0, 0, 0, 0, 5], [0, 3, 0, 7, 0, 0, 0, 5, 0], [0, 0, 7, 0, 0, 5, 0, 0, 0], [4, 0, 5, 0, 1, 0, 7, 0, 8]], only_one_solution=False) solutions = example.solve() """ Solution 1: [9, 2, 6, 5, 7, 1, 4, 8, 3], [3, 5, 1, 4, 8, 6, 2, 7, 9], [8, 7, 4, 9, 2, 3, 5, 1, 6], [5, 8, 2, 3, 6, 7, 1, 9, 4], [1, 4, 9, 2, 5, 8, 3, 6, 7], [7, 6, 3, 1, 9, 4, 8, 2, 5], [2, 3, 8, 7, 4, 9, 6, 5, 1], [6, 1, 7, 8, 3, 5, 9, 4, 2], [4, 9, 5, 6, 1, 2, 7, 3, 8] Solution 2: [9, 2, 6, 5, 7, 1, 4, 8, 3], [3, 5, 1, 4, 8, 6, 2, 7, 9], [8, 7, 4, 9, 2, 3, 5, 1, 6], [5, 8, 2, 3, 6, 7, 1, 9, 4], [1, 4, 9, 2, 5, 8, 3, 6, 7], [7, 6, 3, 1, 4, 9, 8, 2, 5], [2, 3, 8, 7, 9, 4, 6, 5, 1], [6, 1, 7, 8, 3, 5, 9, 4, 2], [4, 9, 5, 6, 1, 2, 7, 3, 8] """
a_cell_active = False while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.MOUSEBUTTONDOWN: mouse_pressed_pos = event.pos if mouse_pressed_pos[1] <= 450: a_cell_active = True if solve_button.mouse_is_over(mouse_pressed_pos): grid = [list(map(int, row)) for row in grid] puzzle = Sudoku(grid) puzzle.solve() solutions = puzzle.get_solutions() grid = solutions[0] if len(solutions) > 0 else grid grid = [list(map(str, row)) for row in grid] if event.type == pygame.KEYDOWN: if a_cell_active: if event.unicode >= '0' and event.unicode <= '9': grid[i][j] = grid[i][j][:-1] grid[i][j] += event.unicode if event.key == pygame.K_RETURN: a_cell_active = False win.fill(bg) for i in range(10):