我又写了一个不用递归的方法,只有十几行代码。不过也不快,大概1~2分钟才出答案。- n = 8
- moves = [[2, 1], [2, -1], [-2, 1], [-2, -1], [1, 2], [1,-2], [-1, 2], [-1, -2]]
- start = [(7,0)]
- queue = [start]
- while queue:
- q = queue.pop()
- if len(q) == n*n:
- print('Done!')
- print(q)
- break
- loc = q[-1]
- for m in moves:
- x = loc[0] + m[0]
- y = loc[1] + m[1]
- if -1<x<n and -1<y<n and (x,y) not in q:
- queue.append(q + [(x, y)])
复制代码
Done!
[(7, 0), (6, 2), (5, 0), (4, 2), (3, 0), (2, 2), (1, 0), (0, 2), (1, 4), (0, 6), (2, 5), (1, 3), (0, 1), (2, 0), (1, 2), (0, 0), (2, 1), (3, 3), (4, 1), (5, 3), (4, 5), (3, 7), (1, 6), (0, 4), (2, 3), (1, 1), (0, 3), (1, 5), (0, 7), (2, 6), (3, 4), (4, 6), (2, 7), (3, 5), (4, 7), (6, 6), (7, 4), (5, 5), (6, 7), (7, 5), (5, 4), (7, 3), (6, 1), (4, 0), (3, 2), (2, 4), (0, 5), (1, 7), (3, 6), (4, 4), (5, 6), (7, 7), (6, 5), (5, 7), (7, 6), (6, 4), (7, 2), (6, 0), (5, 2), (3, 1), (4, 3), (5, 1), (6, 3), (7, 1)] |