如何创建含Moore邻域的3D lattice igraph对象?
3D Moore邻域晶格图的实现方案
要创建包含Moore邻域(含相邻及对角节点)的3D晶格igraph对象,由于make_lattice默认仅支持von Neumann邻域(仅相邻节点),可以通过手动生成节点坐标与邻域边的方式实现,具体步骤如下:
代码实现
library(igraph) library(rgl) # 定义3D晶格的尺寸(示例为4x4x4) dimensions <- c(4, 4, 4) total_nodes <- prod(dimensions) # 生成所有节点的3D坐标 node_coords <- expand.grid( x = 1:dimensions[1], y = 1:dimensions[2], z = 1:dimensions[3] ) rownames(node_coords) <- 1:total_nodes # 构建Moore邻域的边集合 edge_list <- NULL for (node_idx in 1:total_nodes) { # 获取当前节点的坐标 curr_x <- node_coords$x[node_idx] curr_y <- node_coords$y[node_idx] curr_z <- node_coords$z[node_idx] # 筛选Moore邻域节点:坐标差≤1,且排除自身 neighbor_indices <- which( abs(node_coords$x - curr_x) <= 1 & abs(node_coords$y - curr_y) <= 1 & abs(node_coords$z - curr_z) <= 1 & !(node_coords$x == curr_x & node_coords$y == curr_y & node_coords$z == curr_z) ) # 仅添加单向边(避免重复创建双向边) edge_list <- rbind(edge_list, cbind(node_idx, neighbor_indices[neighbor_indices > node_idx])) } # 创建无向晶格图对象 moore_lattice <- graph_from_edgelist(edge_list, directed = FALSE) # 为节点绑定坐标属性,方便可视化 V(moore_lattice)$x <- node_coords$x V(moore_lattice)$y <- node_coords$y V(moore_lattice)$z <- node_coords$z # 3D可视化 rglplot(moore_lattice, layout = as.matrix(node_coords))
关键说明
- 通过
expand.grid生成所有节点的3D坐标,每个节点对应唯一索引; - 遍历每个节点,筛选出切比雪夫距离为1的节点(即Moore邻域,包含上下、左右、前后及所有对角方向的相邻节点);
- 仅添加
node_idx < neighbor_idx的边,避免重复构建双向边,提升效率; - 最后将坐标绑定到节点属性,直接用于3D可视化。
内容的提问来源于stack exchange,提问作者flee
相关产品推荐
相关产品推荐

