You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4 jaren geleden
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import re
  2. import sys
  3. def solve_sudoku(string):
  4. known = [(i, v) for i, v in enumerate(string) if v != '0']
  5. solved, = map(dict, solve(X, Y, known))
  6. return ''.join(solved[i] for i in range(81))
  7. def solve(X, Y, solution):
  8. for choice in solution:
  9. X = select(X, Y, choice)
  10. for solution in complete(X, Y, solution):
  11. yield solution
  12. def select(X, Y, choice):
  13. fulfilled = Y[choice]
  14. excluded = {y for x in fulfilled for y in X[x]}
  15. return {x: ys - excluded for x, ys in X.items() if x not in fulfilled}
  16. def complete(X, Y, solution):
  17. if not X:
  18. yield solution
  19. else:
  20. for choice in min(X.values(), key=len):
  21. yield from complete(select(X, Y, choice), Y, solution + [choice])
  22. Y, X = {}, {}
  23. for i in range(81):
  24. r = i // 9
  25. c = i % 9
  26. b = r // 3 * 3 + c // 3
  27. for v in '123456789':
  28. choice = (i, v)
  29. Y[choice] = {('p', i), ('r', r, v), ('c', c, v), ('b', b, v)}
  30. for x in Y[choice]:
  31. X.setdefault(x, set()).add(choice)
  32. text = sys.stdin.read()
  33. strings = re.split(r'Grid \d\d', text.replace('\n', ''))[1:]
  34. print(sum(int(solve_sudoku(string)[:3]) for string in strings))