酷代码 AI
菜单
服务商

A* 算法:高效实现路径搜索的 Java 代码解析

+ Math.abs(node.getY() - endnode.getY()); double distancefromstart = graph.getDistance(startnode, node); return distancetoend + distancefromstart; } public List<node> search() { Queue<node> queue = new PriorityQueue<>(Comparator.comparingDouble(this::heuristic)); queue.add(startnode); Map<node, Double> gscore = new HashMap<>(); gscore.put(startnode, 0.0); Map<node, node> cameFrom = new HashMap<>(); while (!queue.isEmpty()) { node current = queue.poll(); if (current.equals(endnode)) { return reconstructPath(cameFrom, current); } for (edge edge : graph.getOutgoingEdges(current)) { node neighbor = edge.getDestinationNode(); double tentativeGscore = gscore.get(current) + edge.getLength(); if (!gscore.containsKey(neighbor) || tentativeGscore < gscore.get(neighbor)) { gscore.put(neighbor, tentativeGscore); double fscore = tentativeGscore + heuristic(neighbor); queue.remove(neighbor); queue.add(neighbor); cameFrom.put(neighbor, current); } } } return null; } private List<node> reconstructPath(Map<node, node> cameFrom, node current) { List<node> path = new ArrayList<>(); path.add(current); while (cameFrom.containsKey(current)) { current = cameFrom.get(current); path.add(current); } Collections.reverse(path); return path; } } ######[AI写代码神器 | 1121点数解答 | 2024-10-27 10:09:56]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]