我已经在这个问题上做了很多工作,并且真的接近尾声。总体目标是在两个五个字母的单词之间创建最小长度的单词阶梯,其中阶梯的每个“梯级”与前一个单词不同一个字母。例如:
[heads, heals, hells, halls, hails, tails]
程序从你必须输入一个开始和结束字以及你想要的梯子的长度开始,程序必须解决它。我已经走得很远了,所以我会省略很多细节来解释我目前的情况。
假设我要从“宝贝”到“孩子”,我正在寻找一个 10 个字母的单词阶梯。
我有数千对单词,其中两对是一个不同的字母。这里只是其中一些配对的一小部分。
[(bares, babes), (banes, babes), (bates, babes), (babel, babes), (bases, babes), (bales, babes)...] etc.
这种情况持续了很长时间,但在那里可以保证我的目标词存在,并且在我的起始词(babes)和结束词(child)之间有一条路径,并且那个梯子是 10 个词长。
我该如何做到这一点?
编辑:我已经实现了一个图表,并且正在使用 BFS 从开始词到结束词,这很有效。
public List<T> minLengthPath(T src, T dest, int length)
{
T start = src;
Deque<T> queue = new LinkedList<T>(); //Holds items to visit
Queue<List<T>> ladder = new LinkedList<List<T>>(); //Holds all the ladders?
Set<T> checker = new HashSet<T>(); //Holds visited items
queue.add(start);
checker.add(start);
while(!queue.isEmpty()){
T slot = queue.remove();
if(slot.equals(dest))
{
System.out.println(slot);
return null; //Should be returning ladder
}
Set<Pair<Integer, T>> thing = this.edges.get(slot);
Set<T> edges = findEdges(thing); //Returns the edges of the node
Iterator<T> check = edges.iterator();
for(int a = 0; a < edges.size(); a ++)
{
T hole = check.next();
if(!checker.contains(hole))
{
checker.add(hole);
queue.add(hole);
}
}
}
return null;
}