我正在尝试编写一种方法,如果两个节点之间的距离小于图中的5,则该方法将返回true。我尝试用最小距离算法编写,如下所示:
class Movie{ //this is the node in the graph
String name;
List<Movie> movies;
}
private static boolean isgoodMovies(Movie origin, Movie destination){
Queue<Movie> nextToVisit = new LinkedList<>();
Set<Movie> visited = new HashSet<>();
HashMap<Movie, Integer> distances = new HashMap<>();
nextToVisit.add(origin);
distances.put(origin, 0);
while (!nextToVisit.isEmpty()){
Movie visitedNode = nextToVisit.remove();
if(visited.equals(destination)) {break;}
if(!visited.contains(visitedNode)) {continue;}
visited.add(visitedNode);
for (Movie movie : visitedNode.movies) {
nextToVisit.add(movie);
distances.put(movie, distances.get(visitedNode) + 1);
}
}
return distances.get(origin) < 5;
}
通过修改最小距离算法,我根据原始节点的距离返回布尔值。我想以一种不使用哈希图或任何集合的方式对其进行优化,仅使用一个距离变量即可。您认为有可能吗?
答案 0 :(得分:2)
如果电影的数量不多,则可以在此处使用递归(如果方法调用的数量超过最大堆栈深度,则可以获取StackOverflowError
)。因此,除了Collection
之外,您不会使用任何visited
:
private static boolean isGoodMovies(Movie origin, Movie destination) {
Set<Movie> visited = new HashSet<>();
return isGoodMovies(origin, destination, visited, 0);
}
private static boolean isGoodMovies(Movie current, Movie destination, visited, int depth) {
if (depth >= 5) {
return false;
}
if (destination.equals(current)) {
return true;
}
boolean isGood = false;
for (Movie child : current.movies) {
if (!visited.contains(child) {
visited.add(child);
isGood |= isGoodMovies(child, destination, depth + 1);
}
}
return isGood;
}