0

I want to get all the longest shortest paths for iGraph object. There is this function

get.diameter (graph, directed = TRUE, unconnected = TRUE) 

But it returns only one path. So if there are many shortest paths of the length of the diameter, then it returns the first one found

Ali Zuhair
  • 303
  • 4
  • 17
  • have you tried `shortest.paths(graph)`? – mysteRious Apr 20 '18 at 04:42
  • Yeah it returns a matrix of vertices and values for all the shortest paths. I need a way to return only the vertices that has the longest shortest path. – Ali Zuhair Apr 20 '18 at 04:47
  • 1
    I don't think such a function exists. Why not take all the shortest paths and then extract the longest ones? – gfgm Apr 20 '18 at 07:10

1 Answers1

0

You can easily extract which nodes are connected at what lengths using the shortest-distance matrix returned by shortest.paths(graph). In R, you can use which() and arr.ind=TRUE like so:

longest.shortest.paths <- function(graph){
    # Return edgelist of all node-pairs between which the shortest path
    # in a graph are the longest shortest path observed in that graph.

    # Get all the shortest paths of a graph
    shortest.paths = shortest.paths(graph)

    # Make sure that there are no Inf-values caused by isolates in the graph
    shortest.paths[shortest.paths == Inf] <- 0

    # What nodes in the distance matrix are linked by longest shortest paths?
    el <- which(shortest.paths==max(shortest.paths), arr.ind=TRUE)
    colnames(el) <- c("i","j")
    (el)
}

graph <- erdos.renyi.game(100, 140, "gnm", directed=FALSE)
longest.shortest.paths(graph)
nJGL
  • 819
  • 5
  • 17
  • What I want to solve is this question : "Color the nodes along the diameter which means color only the nodes that pass through the longest shortest path" So I want to know the nodes for every longest shortest path in the network and colour them on the graph. I can't fully understand what i and j represent in your answer. They don't represent the nodes, as they're returning numbers which I don't have as nodes. – Ali Zuhair Apr 21 '18 at 21:10
  • Ah. You should try to specify your problem in the question. I thought you were looking to get all the longest shortest paths for an iGraph object. The function I provided does only that. It returns a matrix of node-pairs (from `i` to `j`) on each row. Between those nodes the shortest path equals the graph's longest shortest path. Try `shortest_paths(graph, to=i, from=j)` to extract the nodes along each path. Consider asking a new question about how to colour all nodes in the shortest paths between all node-pairs between which the shortest path-length equals the diameter of that graph. – nJGL Apr 23 '18 at 12:43