public bool doAStarSearch(Vector2Int from, Vector2Int to) { ArrayList open = new…
- User
public bool doAStarSearch(Vector2Int from, Vector2Int to) { ArrayList open = new ArrayList(); ArrayList close = new ArrayList();
map.createMapNodes(); MapNode target = map.getMapNode(to); MapNode start = map.getMapNode(from); //以下第15周A星算法填空 start.g = 0; start.h = (Mathf.Abs(target.pos.x - start.pos.x) + Mathf.Abs(target.pos.y - start.pos.y)) * 20; start.f = start.g + start.h; open.Add(start); int f; int g; int h; while (open.Count != 0) { MapNode node = findMinCostNode(open); open.Remove(node); if (node == target) { generatePath(node); return true; } close.Add(node); Vector2Int parentPos = node.pos; for (int i = 0; i < 8; ++i) { Vector2Int adjacent = parentPos + dirs[i]; if (!map.canPassWithRowCol(adjacent)) continue; MapNode adjacentNode = map.getMapNode(adjacent);// [map.mapNodes objectAtIndex:adjacent.y * COLS + adjacent.x]; g = node.g + (i % 2 == 0 ? 10 : 14); h = (Mathf.Abs(target.pos.x - adjacent.x) + Mathf.Abs(target.pos.y - adjacent.y)) * 10; f = g + h; //在open list中 if (open.Contains(adjacentNode)) { if (adjacentNode.g > g) { adjacentNode.f = f; adjacentNode.g = g; adjacentNode.h = h; adjacentNode.parent = node; } continue; } //在close list中 if (close.Contains(adjacentNode)) { continue; } //不在open/close list中 adjacentNode.f = f; adjacentNode.g = g; adjacentNode.h = h; adjacentNode.parent = node; open.Add(adjacentNode); } } //以上填空 return false; }对close list中节点的再处理,对open list中f有多个最小值的情况,选取h最小的节点优先处理,从而避免探索一些不必要的节点;实现改进的A*算法。
Assistant
To implement the improved A* algorithm that prioritizes nodes with the smallest h value when there are multiple nodes with the same minimum f value in the open list, you can modify the function to consider both f and h values. Here's the updated code: