This problem maps to the longest path problem, from Graph Theory: Each word is a node in a graph, and two nodes have a directed edge between them if the second word begins with the last character of the first word. This problem is NP-hard. This means that you can only solve it optimally if the number of words is small. If the number of words is big, then different heuristics can be tried, yielding sub-optimal, but perhaps good enough results.
If the number of words is less than 20, and there are probably only few edges for each edge, then is should be possible to enumerate all possible acyclic paths. Then you just need to choose the longest one.
def generate_all_paths(graph):
paths = []
for node in graph.nodes:
paths.append(generate_all_paths_beginning_at_node(n,graph))
return paths
def generate_all_paths_beginning_at_node(start_node,graph):
paths = []
reduced_graph = extract_node_from_graph(graph,start_node)
for next_node in graph.get_nodes_that_have_an_edge_from(start_node)
sub_paths = generate_all_paths_beginning_at_node(next_node,reduced_graph)
paths.append([[start_node] + p for p in sub_paths]) # Add start_node to all paths generated from the reduced_graph.
if paths==[]: # No edge coming out of start_node
paths = [[start_node]] # The only solution is a path of length 0 (one node).
return paths