I would suggest an adjacency map<string, list<string> to represent the graph. It maps the node graph (a word in our case) to a list of neighboring nodes (i.e., All words within a distance == 1).
How to fill this card? First, put the dictionary into sets of words with the same length set<string> wordset[MAX_WORD_LENGTH] and fill in the map as follows.
map<string, list<string>> adjacency_map for each wordset in wordset array for each w1 in wordset for each w2 in wordset if one_char_off(w1, w2) {
The one_char_off(string w1, string w2) function checks if the distance between w1 and w2 is 1.
int diff = 0 for i in [0, w1.length) // both w1 and w2 have the same length if w1[i] != w2[i] if ++diff > 1 return false return diff == 1
The update(map<string, list<string>> adjacency_map, string w1, string w2) function update(map<string, list<string>> adjacency_map, string w1, string w2) adds a pair of adjacent words w1 and w2 to the adjacent map.
source share