答案 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)},
它对应于您发布的图像中节点之间的连接,每隔两行向左拉一点,以使其与上面和下面的节点垂直对齐。
请原谅质量差的图纸。