inp_src = 19 inp_dest = 37 def answer(src, dest): graph_of_valid_moves = make_graph() required_moves = 0 print graph_of_valid_moves[src] list_of_paths = shortest_path(graph_of_valid_moves, src, dest) return len(list_of_paths)-1 def make_graph(): temp_dict = {} for i in range(0,8): for j in range(0,8): temp_dict[(i * 8) + j] = map(lambda x: (x[0] * 8) + x[1], generate_legal_moves(i,j,8)) return temp_dict def shortest_path(graph, start, goal): try: return next(breadth_search(graph, start, goal)) except StopIteration: return None def generate_legal_moves(x,y,bdSize): newMoves = [] moveOffsets = [(-1,-2),(-1,2),(-2,-1),(-2,1), ( 1,-2),( 1,2),( 2,-1),( 2,1)] for i in moveOffsets: newX = x + i[0] newY = y + i[1] if is_legal(newX,bdSize) and \ is_legal(newY,bdSize): newMoves.append((newX,newY)) return newMoves def is_legal(x,bdSize): if x >= 0 and x < bdSize: return True else: return False def breadth_search(graph, start, goal): queue = [(start, [start])] while queue: (vertex, path) = queue.pop(0) for next in graph[vertex]: if next == goal: yield path + [next] else: queue.append((next, path + [next])) print answer(inp_src, inp_dest)