format
This commit is contained in:
parent
b626f667d9
commit
1833258f34
44
navigate.py
44
navigate.py
@ -1,15 +1,5 @@
|
|||||||
import heapq
|
import heapq
|
||||||
|
|
||||||
# 停车场状态矩阵
|
|
||||||
parking_lot = [
|
|
||||||
[3, 2, 2, 0, 2, 2, 2],
|
|
||||||
[3, 1, 1, 0, 1, 1, 1],
|
|
||||||
[0, 0, 0, 0, 0, 0, 0]
|
|
||||||
]
|
|
||||||
|
|
||||||
# 起点和终点(行, 列)
|
|
||||||
start = (0, 3)
|
|
||||||
goal = (1, 1)
|
|
||||||
|
|
||||||
# 可行走的位置(即值为0,或目标位置)
|
# 可行走的位置(即值为0,或目标位置)
|
||||||
def is_walkable(pos):
|
def is_walkable(pos):
|
||||||
@ -18,10 +8,12 @@ def is_walkable(pos):
|
|||||||
return parking_lot[r][c] == 0 or pos == goal
|
return parking_lot[r][c] == 0 or pos == goal
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
# 曼哈顿距离作为启发函数
|
# 曼哈顿距离作为启发函数
|
||||||
def heuristic(a, b):
|
def heuristic(a, b):
|
||||||
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
||||||
|
|
||||||
|
|
||||||
# A*搜索
|
# A*搜索
|
||||||
def a_star(start, goal):
|
def a_star(start, goal):
|
||||||
open_set = []
|
open_set = []
|
||||||
@ -41,7 +33,7 @@ def a_star(start, goal):
|
|||||||
return path[::-1] # 反转
|
return path[::-1] # 反转
|
||||||
|
|
||||||
# 邻接节点(上下左右)
|
# 邻接节点(上下左右)
|
||||||
for dr, dc in [(-1,0), (1,0), (0,-1), (0,1)]:
|
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
|
||||||
neighbor = (current[0] + dr, current[1] + dc)
|
neighbor = (current[0] + dr, current[1] + dc)
|
||||||
|
|
||||||
if not is_walkable(neighbor):
|
if not is_walkable(neighbor):
|
||||||
@ -56,13 +48,25 @@ def a_star(start, goal):
|
|||||||
|
|
||||||
return None # 找不到路径
|
return None # 找不到路径
|
||||||
|
|
||||||
# 执行 A* 路径搜索
|
|
||||||
path = a_star(start, goal)
|
|
||||||
|
|
||||||
# 输出结果
|
if __name__ == "__main__":
|
||||||
if path:
|
# 停车场状态矩阵
|
||||||
print("找到路径:")
|
parking_lot = [
|
||||||
for step in path:
|
[3, 2, 2, 0, 2, 2, 2],
|
||||||
print(step)
|
[3, 1, 1, 0, 1, 1, 1],
|
||||||
else:
|
[0, 0, 0, 0, 0, 0, 0]
|
||||||
print("找不到路径。")
|
]
|
||||||
|
|
||||||
|
# 起点和终点(行, 列)
|
||||||
|
start = (0, 3)
|
||||||
|
goal = (1, 1)
|
||||||
|
# 执行 A* 路径搜索
|
||||||
|
path = a_star(start, goal)
|
||||||
|
|
||||||
|
# 输出结果
|
||||||
|
if path:
|
||||||
|
print("找到路径:")
|
||||||
|
for step in path:
|
||||||
|
print(step)
|
||||||
|
else:
|
||||||
|
print("找不到路径。")
|
||||||
|
Loading…
Reference in New Issue
Block a user