如何生成矩形蜂窝网络

时间:2018-06-19 13:01:14

标签: python r igraph graph-theory

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

enter image description here

图的“中心”处的顶点应分别具有6条边,图的“边”处的顶点应具有2条,3条或5条边。

1 个答案:

答案 0 :(得分: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)

输出:

{(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

请原谅质量差的图纸。