fork download
  1. import random
  2.  
  3. n = 10
  4. startPosition = (-1, -1) # random if (-1, -1)
  5. possibleMoves = [(3, 0), (2, 2), (0, 3), (-2, 2), (-3, 0), (-2, -2), (0, -3), (2, -2)]
  6.  
  7. nSquared = n * n
  8. orderTable = []
  9.  
  10.  
  11. def Solve():
  12. global orderTable
  13. orderTable = [[0 for x in range(n)] for y in range(n)]
  14.  
  15. x, y = startPosition
  16. if x == y == -1:
  17. x, y = random.randrange(n), random.randrange(n)
  18. orderTable[y][x] = 1
  19.  
  20. for alreadyOrdered in range(1, nSquared):
  21. nx, ny = NextFrom(x, y)
  22. if nx == ny == -1:
  23. return False
  24. orderTable[ny][nx] = alreadyOrdered + 1
  25. x, y = nx, ny
  26. return True
  27.  
  28.  
  29. def PrintSolution():
  30. maxDigits = len(str(nSquared))
  31. for row in orderTable:
  32. print(' '.join((f'{value:{maxDigits}}' for value in row)))
  33.  
  34.  
  35. def NextFrom(x, y):
  36. nx, ny = -1, -1
  37. minDegree = len(possibleMoves) + 1
  38. for dstX, dstY in ValidDestinationsFrom(x, y):
  39. dstDegree = CalculateDegreeOf(dstX, dstY)
  40. if dstDegree < minDegree:
  41. minDegree = dstDegree
  42. nx, ny = dstX, dstY
  43. return nx, ny
  44.  
  45.  
  46. def InBounds(x, y):
  47. return 0 <= x < n and 0 <= y < n
  48.  
  49.  
  50. def ValidDestinationsFrom(x, y):
  51. for dx, dy in possibleMoves:
  52. nx, ny = x + dx, y + dy
  53. if InBounds(nx, ny) and orderTable[ny][nx] == 0:
  54. yield nx, ny
  55.  
  56.  
  57. def CalculateDegreeOf(x, y):
  58. return sum(1 for dst in ValidDestinationsFrom(x, y))
  59.  
  60.  
  61. solutionFound = False
  62. while not solutionFound:
  63. solutionFound = Solve()
  64. PrintSolution()
  65.  
Success #stdin #stdout 0.02s 11720KB
stdin
Standard input is empty
stdout
 19  64  32  20  77  35   7  78  36   8
 90  12  29  89  11  28  59  10  27  58
 31  21  86  65  33  79  76  34   6  75
 18  63  91  25  72  92  26  73  37   9
 87  13  30  88  85  66  60  98  67  57
 51  22   1  70  49  80  71  93   5  74
 17  62  96  24  61  97 100  56  38  99
 42  14  50  43  84  69  48  81  68  47
 52  23   2  53  95   3  54  94   4  55
 16  44  41  15  45  40  83  46  39  82