I’m pretty new to Java and I have a problem in my code, where I want to find the shortest path from actor to movie to actor to movie to Kevin Bacon. This is stored in a list which would go "Actor A, Movie A, Actor B, Movie B, Kevin Bacon". I thought that the best way of doing this would be to do it recursively. However, I am getting a StackOverflowError.
I store the actors and movies in a HashMap<String, HashSet<String>>. Both actors and movies are keys – if the actor is called, then it returns a HashSet of the movies the actor has been in, and if the movie is called, it returns a HashSet of the actors it has. The findCostars method finds all the actors a given actor has costarred with.
Here is my code. Any help would be seriously appreciated!
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;
}
You’re getting a stack overflow because your search is depth-first, and you don’t exclude the graph nodes you’ve already visited.
Since you probably want the shortest path, try implementing Breadth-first search.