fork download
  1. def find_empty_location(arr, l):
  2. for row in range(9):
  3. for col in range(9):
  4. if arr[row][col] == 0:
  5. l[0] = row
  6. l[1] = col
  7. return True
  8. return False
  9. def used_in_row(arr, row, num):
  10. for i in range(9):
  11. if arr[row][i] == num:
  12. return True
  13. return False
  14. def used_in_col(arr, col, num):
  15. for i in range(9):
  16. if arr[i][col] == num:
  17. return True
  18. return False
  19. def used_in_box(arr, row, col, num):
  20. for i in range(row // 3 * 3, row // 3 * 3 + 3):
  21. for j in range(col // 3 * 3, col // 3 * 3 + 3):
  22. if arr[i][j] == num:
  23. return True
  24. return False
  25. def check_location_is_safe(arr, row, col, num):
  26. return not used_in_row(arr, row, num) and not used_in_col(arr, col, num) and not used_in_box(arr, row, col, num)
  27. def solve_sudoku(arr):
  28. l = [0, 0]
  29. if not find_empty_location(arr, l):
  30. return True
  31. row = l[0]
  32. col = l[1]
  33. for num in range(1, 10):
  34. if check_location_is_safe(arr, row, col, num):
  35. arr[row][col] = num
  36. if solve_sudoku(arr):
  37. return True
  38. arr[row][col] = 0
  39. return False
  40. # 示例数独谜题
  41. grid = [[3, 0, 6, 5, 0, 8, 4, 0, 0],
  42. [5, 2, 0, 0, 0, 0, 0, 0, 0],
  43. [0, 8, 7, 0, 0, 0, 0, 3, 1],
  44. [0, 0, 3, 0, 1, 0, 0, 8, 0],
  45. [9, 0, 0, 8, 6, 3, 0, 0, 5],
  46. [0, 5, 0, 0, 9, 0, 6, 0, 0],
  47. [1, 3, 0, 0, 0, 0, 2, 5, 0],
  48. [0, 0, 0, 0, 0, 0, 0, 7, 4],
  49. [0, 0, 5, 2, 0, 6, 3, 0, 0]]
  50.  
  51. if solve_sudoku(grid):
  52. for i in range(9):
  53. for j in range(9):
  54. print(grid[i][j], end=' ')
  55. print()
  56. else:
  57. print("No solution exists")
Success #stdin #stdout 0.05s 9480KB
stdin
Standard input is empty
stdout
3 1 6 5 7 8 4 9 2 
5 2 9 1 3 4 7 6 8 
4 8 7 6 2 9 5 3 1 
2 6 3 4 1 5 9 8 7 
9 7 4 8 6 3 1 2 5 
8 5 1 7 9 2 6 4 3 
1 3 8 9 4 7 2 5 6 
6 9 2 3 5 1 8 7 4 
7 4 5 2 8 6 3 1 9