# Implementing Word Ladder Game Using Neo4j

Join the DZone community and get the full member experience.

Join For Freeword ladder is a pretty popular game invented by lewis carroll , who is better known as the author of alice in wonderland.

in a word ladder puzzle you must make the change occur gradually by changing one letter at a time. at each step you must transform one word into another word, you are not allowed to transform a word into a non-word. for instance, the word “fool” can be transformed into the word “sage” as

fool

pool

poll

pole

pale

sale

sage

there are many variations of the word ladder puzzle. for example you might be given a particular number of steps in which to accomplish the transformation, or you might need to use a particular word. in this section we are interested in figuring out the smallest number of transformations needed to turn the starting word into the ending word.

however, the best possible solution of the word ladder problem is using graphs, and with neo4j, it is even easier.

here is an outline of where we are going:

- represent the relationships between the words as a graph.
- use the graph algorithm known as breadth first search to find an efficient path from the starting word to the ending word.

building the word ladder graph

our first problem is to figure out how to turn a large collection of words into a graph. what we would like is to have a relation from one word to another if the two words are only different by a single letter. if we can create such a graph, then any path from one word to another is a solution to the word ladder puzzle.

writing the words onto the graph is another beautiful problem altogether.

we could use several different approaches to create the graph we need to solve this problem. let’s start with the assumption that we have a list of words that are all the same length. as a starting point, we can create a vertex in the graph for every word in the list. to figure out how to connect the words, we could compare each word in the list with every other. when we compare we are looking to see how many letters are different. if the two words in question are different by only one letter, we can create an edge between them in the graph. for a small set of words that approach would work fine; however let’s suppose we have a list of 5,110 words. roughly speaking, comparing one word to every other word on the list is an o(n2)algorithm. for 5,110 words, n2 is more than 26 million comparisons.

we can do much better by using the following approach. suppose that we have a huge number of buckets, each of them with a four-letter word on the outside, except that one of the letters in the label has been replaced by an underscore. for example, consider the image below, we might have a bucket labeled “pop_.” as we process each word in our list we compare the word with each bucket, using the ‘_’ as a wildcard, so both “pope” and “pops” would match “pop_.” every time we find a matching bucket, we put our word in that bucket. once we have all the words in the appropriate buckets we know that all the words in the bucket must be connected.

in java, this can be implemented using a map as the obvious solution.. see the snippet below

public class wordgraph { map<string, node> nodemap; graphdatabaseservice graphdb; public wordgraph(){ graphdb = neodatabasehandler.getgraphdatabase(); nodemap = new hashmap<string, node>(); } private node getnode(string word){ if(!nodemap.containskey(word)){ node node = graphdb.createnode(neohelper.wordlabel.word); node.setproperty("word", word); nodemap.put(word, node); } return nodemap.get(word); } public void addedge(string parentword, string childword){ node parentnode = getnode(parentword); node childnode = getnode(childword); parentnode.createrelationshipto(childnode, neohelper.relationshiptypes.move); } }

whenever we need an edge created, we just call the method, addedge and it will take care of the rest.

so, we iterate over the buckets and write the words and their relationships to the graph, for (list<string> mappedwordsparent : wordmap.values()) {

for (string parentword : mappedwordsparent) { for (string childword : mappedwordsparent) { if(!childword.equals(parentword)){ wordgraph.addedge(parentword, childword); } } } }

the graph created using a minimum set of words will look like the one below, (apologies for the clutter in the relationship names)

once, we have the graph ready, we can do a decent traversal to get the required path. let us assume, we are trying to find a path from
**
fool
**
to
**
sage
**

the graph algorithm we are going to use is called the “breadth first search” algorithm.
**
breadth first search
**
(
**
bfs
**
) is one of the easiest algorithms for searching a graph.

from a very neat post that i came across

given a graph g and a starting vertex s, a breadth first search proceeds by exploring edges in the graph to find all the vertices in g for which there is a path from s. the remarkable thing about a breadth first search is that it finds

allthe vertices that are a distance k from s before it findsanyvertices that are a distance k+1. one good way to visualize what the breadth first search algorithm does is to imagine that it is building a tree, one level of the tree at a time. a breadth first search adds all children of the starting vertex before it begins to discover any of the grandchildren.

implementing this on our own, let us save that for another day. neo4j provides a neat traversal framework .

lets have a look at the code,

graphdb .traversaldescription().breadthfirst() .relationships(neohelper.relationshiptypes.move) .evaluator(evaluators.includewhereendnodeis(endnode)) .traverse(startnode)

it's pretty straight forward. we traverse through relationships named move ( which is the only relationship we have in the graph ). we use an
evaluator
, which decides what to be returned as the output of a traversal, and in this case, we pass the node corresponds to the endword. so, whenever the traversal reaches the endword ( in this case
**
sage
**
), it returns the corresponding path. the complete code can be found in
github
.

once, we have the path, printing it to standard out yields,

fool

pool

poll

pall

pale

sale

sage

which is pretty much what we expected.

much content has been adopted from this book , which is the one place you can start to understand data structures in python.

Published at DZone with permission of Nikhil Kuriakose. See the original article here.

Opinions expressed by DZone contributors are their own.

Comments