Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Fully Commented solution in Clear category for The Shortest Knight's Path by tobytobytoby
def checkio(cells):
start = [ord(cells[0])-96,int(cells[1])] #As coordinates
end = [ord(cells[3])-96,int(cells[4])] #As coordinates
moves = [[2,1],[1,2],[-1,2],[-2,1],[-2,-1],[-1,-2],[1,-2],[2,-1]] #Adding any of these moves to the current coordinates gives a valid target square coordinate
length, spaces, turns = 1,[start],0 #Spaces = 'squares visitable after so many turns'
while end not in spaces: #Loop until the end coordinates are among the visitable coordinates
for i in spaces[0:length]: #Examines each of the currently visitable coordinates
for j in moves: #Looks at all knight moves
x = list(map(sum, zip(i,j))) #Examines all possible target squares
if x not in spaces and 0 < x[0] < 9 and 0 < x[1] < 9: #Ignores repeats and any coordinate that isn't on the 8x8 grid
spaces.append(x) #All possible knight targets added to spaces
turns+=1 #Turn count
length = len(spaces) #Used in the first iterator to ensure is doesn't examine newly appended coordinates
return turns #Yay!
if __name__ == "__main__":
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio("b1-d5") == 2, "1st example"
assert checkio("a6-b8") == 1, "2nd example"
assert checkio("h1-g2") == 4, "3rd example"
assert checkio("h8-d7") == 3, "4th example"
assert checkio("a1-h8") == 6, "5th example"
July 5, 2014
Comments: