【问题标题】:how to check if there exists a unique shortest path between two vertices in igraph如何检查igraph中两个顶点之间是否存在唯一的最短路径
【发布时间】:2019-12-23 02:00:29
【问题描述】:

我想用 igraph 确定两个顶点之间是否存在唯一的最短路径或多个最短路径。如果我使用length(all_shortest_paths(g, i,j),那实际上对我有帮助,但我觉得有很多冗余操作。我宁愿先用get.shortest.paths(g, i,j) 获得一条最短路径,然后看看是否还有另一条路径。但是,我无法弄清楚如何做到这一点。

谁能帮我确定是否有另一条最短路径不同于get.shortest.paths(g, i,j)获得的第一条最短路径?

这是一个示例图

library(igraph)
data <- read.table(text="
1 2
1 4
1 5
2 3
2 4
3 4
5 7
5 8
3 6", header=FALSE)
gmatrix <- data.matrix(data, rownames.force = NA) #convert into a matrix to use in igraph
g <- graph_from_edgelist(gmatrix, directed = FALSE) 

例如,如果我想找到从 1 到 3 的最短路径,我使用all_shortest_paths(g, 1,3),它会给出以下结果。

$res
$res[[1]]
+ 3/9 vertices, from 634c426:
[1] 1 4 3

$res[[2]]
+ 3/9 vertices, from 634c426:
[1] 1 2 3

我想要的是获得第一条最短路径。比如

get.shortest.paths(g, 1,3)
$vpath
$vpath[[1]]
+ 3/9 vertices, from 634c426:
[1] 1 2 3

现在,我想看看是否有与[1] 1 2 3 不同的路径。在更大的图中,由于有数十条可能的最短路径,我不想使用all_shortest_paths(g, i,j) 进行查询。

总的来说,我的问题是:如何检查两个顶点之间是否存在唯一的最短路径?我将给出两个顶点作为我的输入,作为回报,我应该得到 TRUE 或 FALSE,指示是否存在唯一的最短路径。

【问题讨论】:

  • 你想退回什么?特定的顶点序列? T 或 F 表示是否存在不止一条最短路径?最短路径的数量?
  • @paqmo 我只需要true或false,是否存在唯一路径。
  • @paqmo 我在您的回答下留下了评论,但是,我找不到在那里标记您的用户名的方法。如果您能回答我的问题,我将不胜感激。
  • 知道了。我误解了。 length(all_shortest_paths(g, 1,3)$res) &gt; 1 怎么样?
  • 这不会在多项式时间内运行。如果我使用length(all_shortest_paths(g, i,j),则需要很长时间才能解决大规模图形的这个问题。我不需要找到所有这些。事实上,确定一条额外的路径对我来说就足够了。

标签: r igraph graph-theory shortest-path


【解决方案1】:

在收到How to assign edge weights to certain edges in R igraph 的回复后,这是一种解决方案。请注意,初始网络是一个没有边权重的无向图。

p <- get.shortest.paths(g, i, j)$vpath[[1]] #shortest path between node i and node j
g <- set_edge_attr(g, "weight", value = ifelse(E(g) %in% E(g, path = p), 1.50, 1)) #Assign slightly larger edge weights to the edges existing in path p
q <- get.shortest.paths(g, i,j , weights = E(g)$weight)$vpath[[1]] #recalculate the shortest path with edge weights
g <- delete_edge_attr(g, "weight")
if(all(p %in% q))
#If paths p and q are the same, then the shortest path is unique

但是,由于运行时间长,这绝对不是一个好的解决方案。当我对 400 个节点尝试此方法时,需要几分钟才能停止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2015-11-23
    • 2016-03-26
    • 1970-01-01
    • 2021-05-25
    • 2012-12-01
    • 2021-05-18
    相关资源
    最近更新 更多