我很新的Java和我在我的代码,在这里我想找到凯文·贝肯从演员到电影演员为影片的最短路径有问题。这存储在list
中,其将变为"Actor A, Movie A, Actor B, Movie B, Kevin Bacon"
。我认为这样做的最好方法就是去做recursively
。但是,我得到StackOverflowError
。Java中的Kevin Bacon路径给出了堆栈溢出?
我存储演员在HashMap<String, HashSet<String>>
和电影。无论演员和电影是keys
- 如果演员被调用,则返回电影的演员一直处于一个HashSet
,如果电影被调用,它返回一个HashSet
演员它有。该findCostars
方法找到所有演员给定演员已与联袂主演。
这是我的代码。任何帮助将被认真感谢!
public List<String> findBaconPath (String actor) throws IllegalArgumentException {
ArrayList<String> actors = new ArrayList<String>();
actors.add(actor);
ArrayList<String> path = helper(actors, actor);
return path;
}
public ArrayList<String> helper(ArrayList<String> curr, String actor) {
ArrayList<String> list = new ArrayList<String>();
HashSet<String> movies = myMovies.get(actor);
ArrayList<String> coStars = (ArrayList<String>) findCostars(actor);
Iterator<String> it = movies.iterator();
while (it.hasNext()) {
String next = it.next();
HashSet<String> movAct = myMovies.get(next);
if (movAct.contains("Bacon, Kevin")) {
list.add("Bacon, Kevin");
list.add(next);
list.add(actor);
return list;
} else {
Iterator<String> itAct = coStars.iterator();
while(itAct.hasNext()) {
curr.add(next);
String nextActorValue = itAct.next();
curr.add(nextActorValue);
helper(curr, nextActorValue);
}
}
}
return null;
}
你想那烂番茄的收视率和最小的最短路径或路径?如果是后者,你可能需要小心周围涉及* Tremors *续集的净负循环。 –