I have written a small game about knight's tour problem in Python.
When I finished the algorithm part of the game, I found it run about 0.01 second to find a successful path of a 8*8 chess board. But when I run it on the computer of my office, it cost over 10 seconds to find the same path. Then I tried it on three other computers, the result is about 0.005, 6 and 8 seconds.
Why the execution speed of the same code has a huge difference on the five computers? The result is 0.005, 0.010, 6, 8 and 10 seconds. We can see the difference can be over 1000 times. The hardware of computers whose speeds are 6s and 8s are similar or better than 0.01's. And if the hardware affects the speed, it can't be that much -- about 1000 times.
I have corrected my code, the first edition has a mistake. I am using Python 3.6. And the test has been changed to 8*8 size, I'm sorry that I misremembered.
The following is the code.
import sys
import time
def init_path(size):
allow = []
for i in range(size):
for j in range(size):
allow.append([i, j])
return allow
def get_next_choice(step, hist, raws, allow):
num = 0
for raw in raws:
nextstep = [raw[i]+step[i] for i in range(2)]
if nextstep in allow and nextstep not in hist:
num += 1
return num
def search_next(size, pos, history, allow):
nextsteps = {}
raws = [[1,2], [1,-2], [2,1], [2,-1], [-1,2], [-1,-2], [-2,1], [-2,-1]]
if len(history) == size*size:
return True
for raw in raws:
nextstep = [raw[i]+pos[i] for i in range(2)]
if nextstep in allow and nextstep not in history:
next_choice = get_next_choice(nextstep, history, raws, allow)
nextsteps[next_choice] = nextstep
sorted(nextsteps.items())
for nextstep in nextsteps.values():
history.append(nextstep)
back = search_next(size, nextstep, history, allow)
if back:
return True
else:
history.pop()
else:
return False
def search_path(size, history):
allow = init_path(size)
position = history[-1]
back = search_next(size, position, history, allow)
if back:
return history
else:
return False
atime = time.time()
path = search_path(8, [[0,0]])
btime = time.time()
print(btime - atime)