-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathastar.py
66 lines (51 loc) · 2 KB
/
astar.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Node:
def __init__(self, position, parent=None):
self.position = position
self.parent = parent
self.g = 0
self.h = 0
self.f = 0
def __eq__(self, other):
return self.position == other.position
def heuristic(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1]) # 使用曼哈顿距离
def astar(grid, start, end):
start_node = Node(start, None)
end_node = Node(end, None)
open_list = []
closed_list = []
open_list.append(start_node)
while len(open_list) > 0:
current_node = open_list[0]
current_index = 0
for index, item in enumerate(open_list):
if item.f < current_node.f:
current_node = item
current_index = index
open_list.pop(current_index)
closed_list.append(current_node)
if current_node == end_node:
path = []
current = current_node
while current is not None:
path.append(current.position)
current = current.parent
return path[::-1] # Return reversed path
children = []
for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0)]: # 相邻方格
node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])
if node_position[0] > (len(grid) - 1) or node_position[0] < 0 or node_position[1] > (len(grid[len(grid)-1]) -1) or node_position[1] < 0:
continue
if grid[node_position[0]][node_position[1]] != 0:
continue
new_node = Node(node_position, current_node)
children.append(new_node)
for child in children:
if child in closed_list:
continue
child.g = current_node.g + 1
child.h = heuristic(child.position, end_node.position)
child.f = child.g + child.h
if child in open_list:
continue
open_list.append(child)