我正在尝试制作一个程序,在标准词典文本文件中的任意两个单词之间打印出一个单词梯形图,但它仍然卡在一个单词上。当我尝试“天使”和“恶魔”时,它总是“蔬菜”。
以下是代码:
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Stack;
class WordLadder
{
static ArrayList words=new ArrayList();
public static void main(String[] args)
{
EasyReader dictFile=new EasyReader("C:\\dict.txt");
EasyReader input=new EasyReader();
String o;
while ((o = dictFile.readWord()) != null)
{
words.add(o.toLowerCase());
}
System.out.println("What is the starting word?");
String start=input.readLine();
System.out.println("What is the ending word?");
String end=input.readLine();
if(start.length()!=end.length())
{
System.out.println("The words have to be the same length!");
System.exit(0);
}
boolean isfound=false;
LinkedList q = new LinkedList();
LinkedList procq = new LinkedList();
Stack starter=new Stack();
starter.push(start);
q.add(starter);
ArrayList used=new ArrayList();
used.add(start);
while(!isfound)
{
Stack process=(Stack)q.removeLast();
System.out.println("finding one-offs for "+process.peek());
ArrayList oneoffs=findOneOffWords(process.peek().toString(), used);
System.out.println(oneoffs);
if(!oneoffs.isEmpty())
{
for(int i=0;i<oneoffs.size();i++)
{
Stack toproc=process;
System.out.println("processing stack: "+toproc);
toproc.add(oneoffs.get(i));
while(q.removeFirstOccurrence((Object)toproc))
{
}
boolean isused=false;
for (Object temp : used)
{
if(toproc.peek().toString().equalsIgnoreCase(temp.toString()))
{
isused=true;
}
}
if(!isused)
{
q.add(toproc);
}
used.add(oneoffs.get(i));
if(toproc.peek().toString().equalsIgnoreCase(end))
{
System.out.println("found solution!");
while(!toproc.empty())
{
System.out.println(toproc.pop().toString());
}
}
}
}
}
}
public static ArrayList findOneOffWords(String word, ArrayList used)
{
ArrayList oneoff=new ArrayList();
for(int i=0;i<167964;i++)
{
if(word.length()==words.get(i).toString().length())
{
int counter=0;
for(int h=0; h<word.length(); h++)
{
if(!word.substring(h,h+1).equalsIgnoreCase(words.get(i).toString().substring(h,h+1)))
{
counter++;
}
}
boolean isused=false;
for (Object temp : used)
{
if(words.get(i).toString().equalsIgnoreCase(temp.toString()))
{
isused=true;
}
}
if(counter==1&&isused==false)
{
oneoff.add(words.get(i));
}
}
}
return oneoff;
}
}