Search code examples
pythonpython-3.xgraphnetworkx

How to create a connected 2D grid graph?


I have a 2-dimensional array that represents a grid. The (numpy) array is as follows:

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

I want to convert that into the following:

enter image description here

I know that grid_2d_graph can connect 4 adjacent nodes. For example, it would connect node M to B, L, N and Y BUT NOT to A, C, X, Z. How would I create such a graph using networkx in python?


Solution

  • Something like this should work:

    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 all nodes
    for i in range(r):
        for j in range(c):
            # connect all neighbors
            for k in range(-1,2):
                for l in range(-1,2):
                    # check if neighbor node index is valid 
                    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]) # connect with neighbor node
    # 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