sudoku_solver.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # Sudoku: 9x9 Spielfeld. Auf jedem Feld ist eine Liste mit möglichen Werten.
  2. # Enthält diese Liste nur einen Wert, ist das der gesuchte Wert für das Feld.
  3. gamefield = [
  4. [[],[7],[],[5],[8],[3],[],[2],[]],
  5. [[],[5],[9],[2],[],[],[3],[],[]],
  6. [[3],[4],[],[],[],[6],[5],[],[7]],
  7. [[7],[9],[5],[],[],[],[6],[3],[2]],
  8. [[],[],[3],[6],[9],[7],[1],[],[]],
  9. [[6],[8],[],[],[],[2],[7],[],[]],
  10. [[9],[1],[4],[8],[3],[5],[],[7],[6]],
  11. [[],[3],[],[7],[],[1],[4],[9],[5]],
  12. [[5],[6],[7],[4],[2],[9],[],[1],[3]]
  13. ];
  14. def fill_empty_fields_with_possible_values():
  15. y = 0
  16. for row in gamefield:
  17. x = 0
  18. for field in row:
  19. if(len(field) == 0):
  20. field = [1,2,3,4,5,6,7,8,9]
  21. row[x] = field
  22. x = x + 1
  23. gamefield[y] = row
  24. y = y + 1
  25. def print_sudoku():
  26. for row in gamefield:
  27. for field in row:
  28. if(len(field) == 1):
  29. print(field, end='')
  30. else:
  31. print('[ ]', end='')
  32. print('')
  33. def solve_by_cell_check():
  34. # for each cell
  35. y = 0
  36. for row in gamefield:
  37. x = 0
  38. for field in row:
  39. # if value is already defined, check next value
  40. if(len(field) == 1):
  41. continue
  42. # for each possible value
  43. for possible_value in field:
  44. print("check value", possible_value, "at (",x,"/",y,") : ",gamefield[y][x])
  45. if(check_row_for_value(x, y, possible_value) or
  46. check_column_for_value(x, y, possible_value) or
  47. check_3x3_for_value(x, y, possible_value)):
  48. # if yes, remove it from possible values
  49. remove_from_possible_values(x, y, possible_value)
  50. print(gamefield[y][x])
  51. # reset x and break to check that field again
  52. x = x - 1
  53. break
  54. x = x + 1
  55. y = y + 1
  56. def remove_from_possible_values(x, y, value):
  57. gamefield[y][x].remove(value)
  58. # i do not explicitely skip the field itself because it is skipped by len check
  59. def check_row_for_value(x, y, value):
  60. for field in gamefield[y]:
  61. if len(field) == 1:
  62. if field[0] == value:
  63. return True
  64. return False
  65. def check_column_for_value(x, y, value):
  66. return False
  67. def check_3x3_for_value(x, y, value):
  68. return False
  69. fill_empty_fields_with_possible_values()
  70. #print(gamefield[0][0])
  71. print_sudoku()
  72. solve_by_cell_check()
  73. #print(gamefield[0][0])
  74. #print_sudoku()