如何生成矩形蜂窝网络

How to generate rectangular honeycomb network

如何生成一个类似图形的对象(在 R 或 Python 中)来表示由连接的六边形组成的规则矩形网络,如下图所示:

图 "center" 处的顶点应各有 6 条边,图 "sides" 处的顶点应有 2、3 或 5 条边。

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

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)}, 

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

画质不好请见谅