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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| import pulp
problem = pulp.LpProblem("Sudoku Problem", pulp.LpMinimize)
choices = pulp.LpVariable.dicts("Choice", (range(1, 10), range(1, 10), range(1, 10)), cat='Binary')
for row in range(1, 10): for col in range(1, 10): problem += pulp.lpSum([choices[row][col][num] for num in range(1, 10)]) == 1
for row in range(1, 10): for num in range(1, 10): problem += pulp.lpSum([choices[row][col][num] for col in range(1, 10)]) == 1
for col in range(1, 10): for num in range(1, 10): problem += pulp.lpSum([choices[row][col][num] for row in range(1, 10)]) == 1
for row in range(1, 10, 3): for col in range(1, 10, 3): for num in range(1, 10): problem += pulp.lpSum([choices[i][j][num] for i in range(row, row + 3) for j in range(col, col + 3)]) == 1
initial_state = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9] ]
for row in range(9): for col in range(9): if initial_state[row][col] != 0: problem += choices[row+1][col+1][initial_state[row][col]] == 1
problem.solve()
solution = [[0]*9 for _ in range(9)] for row in range(1, 10): for col in range(1, 10): for num in range(1, 10): if choices[row][col][num].value() == 1: solution[row-1][col-1] = num
for row in solution: print(row)
|