如何生成矩形蜂窝网络

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

如何生成表示连接六边形的常规矩形网络的类图形对象(在R或Python中),如下图所示:

enter image description here

图形“中心”的顶点应各有6条边,图形“边”的顶点应有2,3或5条边。

python r igraph graph-theory
1个回答
1
投票

您可以创建一个邻接集网格,表示每个单元与之连接的单元格的索引:

class HexGraph:
    def __init__(self, rows, cols):
        self.rows = rows
        self.cols = cols
        self.cells = [[set() for c in range(self.cols)] for r in range(self.rows)]
        self.build_connections()

    def build_connections(self):
        offsets = (((-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, -1)),
                   ((-1, 0), (1, 0), (0, -1), (0, 1), (-1, 1), (1, 1)))
        for rdx, line in enumerate(self.cells):
            for cdx, cell in enumerate(line):
                for dr, dc in offsets[rdx % 2]:
                    r = rdx + dr
                    c = cdx + dc
                    if r >= 0 and r < self.rows and c >= 0 and c < self.cols:
                        cell.add((r, c))

    def __str__(self):
        result = []
        for line in self.cells:
            res = ''
            for cell in line:
                res += str(cell) + ', '
            result.append(res)
        return '\n'.join(result)


if __name__ == '__main__':

    g = HexGraph(5, 4)
    print(g)

output:

{(0, 1), (1, 0)}, {(0, 2), (1, 0), (0, 0), (1, 1)}, {(1, 2), (0, 3), (0, 1), (1, 1)}, {(1, 2), (1, 3), (0, 2)}, 
{(0, 1), (0, 0), (2, 1), (2, 0), (1, 1)}, {(0, 1), (1, 2), (2, 1), (2, 2), (1, 0), (0, 2)}, {(1, 3), (0, 2), (2, 3), (2, 2), (0, 3), (1, 1)}, {(1, 2), (0, 3), (2, 3)}, 
{(3, 0), (1, 0), (2, 1)}, {(3, 0), (3, 1), (2, 0), (2, 2), (1, 0), (1, 1)}, {(1, 2), (3, 2), (3, 1), (2, 1), (2, 3), (1, 1)}, {(1, 2), (3, 2), (1, 3), (3, 3), (2, 2)}, 
{(3, 1), (2, 1), (2, 0), (4, 1), (4, 0)}, {(3, 2), (3, 0), (2, 1), (2, 2), (4, 2), (4, 1)}, {(3, 3), (3, 1), (2, 3), (4, 3), (2, 2), (4, 2)}, {(3, 2), (2, 3), (4, 3)}, 
{(3, 0), (4, 1)}, {(3, 0), (4, 2), (3, 1), (4, 0)}, {(3, 2), (3, 1), (4, 1), (4, 3)}, {(4, 2), (3, 2), (3, 3)}, 

它对应于您发布的图像中节点之间的连接,每个第二行向左拉一点以与其正上方和下方的节点垂直对齐。

enter image description here

enter image description here

请原谅质量差的画。

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