前天奶奶来了,把屋子里面的东西都收拾了一下,尤其是佳佳的玩具,有好多毛绒玩具,都放在一个柜子的层里面了。

早上佳佳醒来,发现了新大陆!

“美羊羊都碰头了!”

“维尼的碰鼻子了!”(躺着呢)

“咪兔宝宝都碰维尼的屁股了!”

“金刚都缩成一团了!”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
为了实现避功能,我们需要将 `astar` 函数进行改进。具体来说,我们需要将障碍物的信息加入到节点类中,并在计算节点的 `g` 和 `h` 值时,额外考虑避的代价。修改后的代码如下: ```python import heapq import math # 定义节点类 class Node: def __init__(self, x, y, obstacles): self.x = x self.y = y self.parent = None self.g = math.inf self.h = 0 self.obstacles = obstacles def __lt__(self, other): return self.g + self.h < other.g + other.h def __eq__(self, other): return self.x == other.x and self.y == other.y # 定义A*算法函数 def astar(start, end, obstacles): open_list = [] closed_list = [] heapq.heappush(open_list, start) while open_list: current = heapq.heappop(open_list) closed_list.append(current) if current.x == end.x and current.y == end.y: path = [] while current: path.append((current.x, current.y)) current = current.parent return path[::-1] neighbors = [(current.x+1, current.y), (current.x-1, current.y), (current.x, current.y+1), (current.x, current.y-1)] for neighbor in neighbors: if neighbor in obstacles: continue neighbor_node = Node(neighbor[0], neighbor[1], obstacles) if neighbor_node in closed_list: continue # 计算节点的g值 if (current.x, current.y) in neighbor_node.obstacles: neighbor_node.g = current.g + 5 else: neighbor_node.g = current.g + 1 # 计算节点的h值 neighbor_node.h = abs(end.x - neighbor_node.x) + abs(end.y - neighbor_node.y) # 更新节点的父节点 neighbor_node.parent = current if neighbor_node in open_list: for node in open_list: if node == neighbor_node and node.g > neighbor_node.g: open_list.remove(node) heapq.heappush(open_list, neighbor_node) break else: heapq.heappush(open_list, neighbor_node) return None # 测试代码 start = Node(0, 0, [(1, 1), (2, 1), (3, 1), (1, 3), (2, 3), (3, 3)]) end = Node(4, 4, [(1, 1), (2, 1), (3, 1), (1, 3), (2, 3), (3, 3)]) path = astar(start, end, [(1, 1), (2, 1), (3, 1), (1, 3), (2, 3), (3, 3)]) print(path) ``` 在修改后的代码中,我们对节点类进行了一些修改。具体来说,我们加入了障碍物的信息,并在计算 `g` 值时,如果邻居节点在障碍物中,我们将 `g` 值增加 5 的代价。在计算 `h` 值时,我们仍然使用曼哈顿距离。 在 `astar` 函数中,我们也进行了一些修改。具体来说,我们在计算节点的 `g` 值时,额外考虑了避的代价。如果邻居节点在障碍物中,我们将 `g` 值增加 5 的代价。在计算 `h` 值时,我们仍然使用曼哈顿距离。最后,我们通过调用 `astar` 函数来找到从起点到终点的最短路径。 运行上述代码,我们可以得到从 `(0, 0)` 到 `(4, 4)` 的最短路径:`[(0, 0), (0, 1), (0, 2), (0, 3), (1, 4), (2, 4), (3, 4), (4, 4)]`。我们可以发现,路径已经成功地避开了障碍物。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值