cod*_*ict 46
这可以建模为图形问题.您可以将这些单词视为图形的节点,并且当且仅当它们具有相同的长度并且在一个char中不同时,才连接两个节点.
您可以预处理字典并创建此图,应如下所示:
stack jack
| |
| |
smack back -- pack -- pick
Run Code Online (Sandbox Code Playgroud)
然后,您可以从单词到表示单词的节点进行映射,为此您可以使用哈希表,高度平衡BST ...
完成上述映射后,您所要做的就是查看两个图节点之间是否存在路径,这可以使用BFS或DFS轻松完成.
因此,您可以将算法汇总为:
preprocess the dictionary and create the graph.
Given the two inputs words w1 and w2
if length(w1) != length(w2)
Not possible to convert
else
n1 = get_node(w1)
n2 = get_node(w2)
if(path_exists(n1,n2))
Possible and nodes in the path represent intermediary words
else
Not possible
Run Code Online (Sandbox Code Playgroud)