如何创建连接的二维网格图?

问题描述 投票:0回答:1

我有一个代表网格的二维数组。 (numpy)数组如下:

dx_grid =[[ "A", "B", "C"],
          [ "L", "M", "N"],
          [ "X", "Y", "Z"]]

我想将其转换为以下内容:

enter image description here

我知道grid_2d_graph可以连接4个相邻节点。例如,它将节点 M 连接到 B、L、N 和 Y,但不连接到 A、C、X、Z。我如何在 python 中使用

networkx
创建这样的图?

python python-3.x graph networkx
1个回答
0
投票

这样的东西应该有效:

import networkx as nx

dx_grid =[[ "A", "B", "C"],
          [ "L", "M", "N"],
          [ "X", "Y", "Z"]]
r, c = len(dx_grid), len(dx_grid[0])

g = nx.Graph()

# add nodes 
for i in range(r):
    for j in range(c):
        g.add_node(dx_grid[i][j], pos=(j,r-i))

# add edges
for i in range(r):
    for j in range(c):
        for k in range(-1,2):
            for l in range(-1,2):
                if i+k >= 0 and i+k < r and j+l >= 0 and j+l < c:
                    if k == 0 and l == 0: continue # avoid self-loops
                    g.add_edge(dx_grid[i][j], dx_grid[i+k][j+l])
# get positions
pos = nx.get_node_attributes(g,'pos')
# draw network with nodes at given positions
plt.figure(figsize=(6,6))
nx.draw(g, 
        pos=pos, 
        node_color='lightblue', 
        with_labels=True,
        node_size=600)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.