我对 Java 很陌生,我的代码中有一个问题,我想找到从演员到电影到演员到电影到 Kevin Bacon的最短路径。这存储在一个list
which would go"Actor A, Movie A, Actor B, Movie B, Kevin Bacon"
中。我认为最好的方法就是这样做recursively
。但是,我得到一个StackOverflowError
.
我将演员和电影存储在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;
}