You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用R语言igraph计算无向图指定节点对的最大路径权重和

基于igraph计算无向图指定节点对最大路径权重和的实现方案

你需要实现的是无向图指定节点对的最大权重路径和计算(多路径场景自动取最大值),可通过改造igraph自带的shortest.paths函数实现,核心逻辑为将边权重取负后求最短路径,再对结果取负还原得到最大权重和,完整实现步骤如下:


步骤1:导入依赖包并修复原始代码笔误

首先加载igraph包,注意原始示例代码中存在对象名笔误(创建graph1却给graph2的边赋值),需先修正:

library(igraph)

步骤2:单路径场景实现

使用你提供的第一组测试数据实现需求,代码如下:

# 单路径场景测试数据
nodeA <- c("ID_1", "ID_2", "ID_3", "ID_4", "ID_5", "ID_16", "Node_30")
nodeB <- c("ID_11", "ID_3", "ID_4", "ID_5", "ID_3", "ID_11", "Node_3")
edge_weight <- c(0.5, 0.9, 0.8, 0.7, 0.5, 0.09, 0.7)
df_1 <- data.frame(nodeA, nodeB, edge_weight)

# 构建无向图
graph1 <- graph_from_data_frame(df_1, directed = FALSE)
E(graph1)$weight <- df_1$edge_weight

# 待查询的节点对
query_pairs <- data.frame(
  nodeA = c("ID_2", "ID_2", "ID_1"),
  nodeB = c("ID_4", "ID_5", "ID_16")
)

# 计算所有节点对的最大路径权重
max_path_dist <- -shortest.paths(graph1, weights = -E(graph1)$weight, mode = "all")

# 提取指定节点对的结果
query_pairs$sum_of_weight <- mapply(function(a,b) max_path_dist[a,b],
                                    query_pairs$nodeA,
                                    query_pairs$nodeB)

运行后输出query_pairs即可得到预期结果:

nodeA nodeB sum_of_weight
1  ID_2  ID_4          1.70
2  ID_2  ID_5          1.40
3  ID_1 ID_16          0.59

步骤3:多路径场景验证

使用你提供的多路径测试数据验证取最大值的逻辑:

# 多路径场景测试数据
nodeA <- c("ID_1", "ID_2",  "ID_4", "ID_5", "ID_16", "Node_30", "ID_6", "ID_2")
nodeB <- c("ID_11", "ID_3",  "ID_5", "ID_3", "ID_11", "Node_3", "ID_3", "ID_4")
edge_weight <- c(0.5, 0.9, 0.8, 0.7, 0.5, 0.09, 0.7, 1.5)
df_2 <- data.frame(nodeA, nodeB, edge_weight)

# 构建无向图
graph2 <- graph_from_data_frame(df_2, directed = FALSE)
E(graph2)$weight <- df_2$edge_weight

# 计算最大路径权重并查询ID_3到ID_4的结果
max_path_dist2 <- -shortest.paths(graph2, weights = -E(graph2)$weight, mode = "all")
cat("ID_3到ID_4的最大路径权重:", max_path_dist2["ID_3", "ID_4"], "\n")

输出结果为2.4,符合取最大路径权重的需求。


可选优化

如果节点对之间不存在连通路径,结果会返回Inf,可通过以下代码过滤无效结果:

query_pairs <- query_pairs[is.finite(query_pairs$sum_of_weight), ]

内容的提问来源于stack exchange,提问作者0Knowledge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:15:07