问题
I'd like to identify if there exist a unique shortest path or multiple shortest paths between two vertices with igraph. If I use length(all_shortest_paths(g, i,j)
, that actually helps me, but I feel like there are so many redundant operations. I rather prefer first to get one shortest path with get.shortest.paths(g, i,j)
, and then see if there is another. However, I could not figure out how to do this.
Can someone help me how to identify whether there is another shortest path different than the first one obtained by get.shortest.paths(g, i,j)
?
Here is an example graph
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)
For instance, if I'd like to find the shortest path from 1 to 3, I use all_shortest_paths(g, 1,3)
, and it gives me the following result.
$res
$res[[1]]
+ 3/9 vertices, from 634c426:
[1] 1 4 3
$res[[2]]
+ 3/9 vertices, from 634c426:
[1] 1 2 3
What I want is to get the first shortest path. For instance
get.shortest.paths(g, 1,3)
$vpath
$vpath[[1]]
+ 3/9 vertices, from 634c426:
[1] 1 2 3
Now, I want to see if there is any other path different than [1] 1 2 3
. In a larger graph, since there are tens of possible shortest paths, I don't want to use all_shortest_paths(g, i,j)
to make that query.
Overall, my question is: how can I check whether there exists a unique shortest path between two vertices or not? I will give two vertices as my input, in return I should get TRUE or FALSE indicating if there is a unique shortest path.
回答1:
After getting responded for How to assign edge weights to certain edges in R igraph, here is one solution. Please note that the initial network is an undirected graph with no edge weights.
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
However, this is definitely not a good solution due to the high running time. When I try this method for 400 nodes, it takes several minutes to stop.
来源:https://stackoverflow.com/questions/57529808/how-to-check-if-there-exists-a-unique-shortest-path-between-two-vertices-in-igra