1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| def is_valid(board, row, col, num): if num in board[row * 9: (row + 1) * 9]: return False if num in [board[i * 9 + col] for i in range(9)]: return False start_row, start_col = 3 * (row // 3), 3 * (col // 3) for i in range(start_row, start_row + 3): for j in range(start_col, start_col + 3): if board[i * 9 + j] == num: return False return True
def solve_sudoku(board): for row in range(9): for col in range(9): if board[row * 9 + col] == 0: for num in range(1, 10): if is_valid(board, row, col, num): board[row * 9 + col] = num if solve_sudoku(board): return True board[row * 9 + col] = 0 return False return True
sudoku_board = [0x00000004, 0x00000000, 0x00000007, 0x00000000, 0x00000000, 0x00000003, 0x00000002, 0x00000000, 0x00000008, 0x00000005, 0x00000000, 0x00000000, 0x00000000, 0x00000002, 0x00000000, 0x00000009, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000002, 0x00000009, 0x00000008, 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000007, 0x00000000, 0x00000009, 0x00000001, 0x00000000, 0x00000004, 0x00000008, 0x00000000, 0x00000000, 0x00000000, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000007, 0x00000000, 0x00000000, 0x00000000, 0x00000003, 0x00000002, 0x00000007, 0x00000000, 0x00000000, 0x00000000, 0x00000006, 0x00000000, 0x00000008, 0x00000006, 0x00000003, 0x00000000, 0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000002, 0x00000000, 0x00000007, 0x00000004, 0x00000000, 0x00000006, 0x00000003, 0x00000000, 0x00000003, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000002, 0x00000000, 0x00000000, 0x00000000] if solve_sudoku(sudoku_board): for i in range(9): row = sudoku_board[i * 9:(i + 1) * 9] print(row) else: print("无解")
|