You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于NetworkX的2D仓库多节点最短路径求解及布局可视化问题

2D仓库多节点最短路径规划与NetworkX实现方案

核心问题明确

  • 仓库节点规则:Z开头为起止点,A/B/C+编号为存储点
  • 移动限制:仅支持水平/垂直移动,相邻节点间距1米(曼哈顿距离逻辑)
  • 指定任务路径:Z00 → A1A1 → C1A4 → Z02

步骤1:构建带真实坐标的仓库图结构

要解决可视化和路径计算问题,核心是给每个节点绑定与仓库实际布局匹配的坐标,示例代码如下:

import networkx as nx
import matplotlib.pyplot as plt

# 初始化无向图(路径可双向通行)
warehouse_graph = nx.Graph()

# 定义节点对应坐标(根据你的仓库实际布局修改数值)
node_coords = {
    "Z00": (0, 0),
    "A1A1": (2, 3),
    "C1A4": (5, 7),
    "Z02": (8, 0),
    "Z01": (0, 8),
    "B1A1": (3, 3)
}

# 添加节点
warehouse_graph.add_nodes_from(node_coords.keys())

# 自动生成相邻节点的边(仅水平/垂直相邻,权重为1)
nodes = list(node_coords.keys())
for i in range(len(nodes)):
    x1, y1 = node_coords[nodes[i]]
    for j in range(i+1, len(nodes)):
        x2, y2 = node_coords[nodes[j]]
        # 判定是否为相邻可通行节点
        if (abs(x1 - x2) == 1 and y1 == y2) or (abs(y1 - y2) == 1 and x1 == x2):
            warehouse_graph.add_edge(nodes[i], nodes[j], weight=1)

步骤2:还原仓库布局可视化

利用手动定义的坐标作为布局参数,即可生成符合实际的可视化图:

plt.figure(figsize=(8, 6))
# 按指定坐标绘制节点
nx.draw(warehouse_graph, pos=node_coords, with_labels=True, node_size=800, node_color="lightblue")
# 可选:显示边权重
edge_labels = nx.get_edge_attributes(warehouse_graph, "weight")
nx.draw_networkx_edge_labels(warehouse_graph, pos=node_coords, edge_labels=edge_labels)
plt.title("2D仓库布局可视化")
plt.show()

步骤3:计算多节点顺序访问的最短路径总距离

将任务拆分为三段独立的最短路径计算,累加总距离即可:

# 定义固定访问顺序
path_sequence = ["Z00", "A1A1", "C1A4", "Z02"]

total_distance = 0
full_path = []

for i in range(len(path_sequence)-1):
    start = path_sequence[i]
    end = path_sequence[i+1]
    # 用Dijkstra算法计算两点间最短路径
    shortest_path = nx.shortest_path(warehouse_graph, source=start, target=end, weight="weight")
    # 路径距离 = 节点数-1(每条边对应1米)
    path_distance = len(shortest_path) - 1
    total_distance += path_distance
    full_path.extend(shortest_path[:-1])  # 避免重复添加中间节点

full_path.append(path_sequence[-1])

print(f"完整最短路径: {' → '.join(full_path)}")
print(f"总路径距离: {total_distance} 米")

关键提示

  • 坐标必须与仓库实际布局完全匹配,否则可视化和路径计算都会出错
  • 若存在不可通行区域,需在添加边时排除对应节点的连接
  • 节点数量较多时,可通过CSV等文件批量导入坐标,减少手动录入工作量

内容的提问来源于stack exchange,提问作者Kapil Mane Deshmukh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 07:35:14