Given a graph of N vertices and the distance between the edges of the vertices stored in tuple T1 = (d11, d12, …, d1n) to Tn = (dn1, dn2, …, dnn)
. Find out a minimum spanning tree of this graph starting from the vertex V1. Also, print the total distance travel needed to travel this generated tree.
Example:
For N =5
T1 = (0, 4, 5, 7, 5)
T2 = (4, 0, 6, 2, 5)
T3 = (5, 6, 0, 2, 1)
T4 = (7, 2, 2, 0, 5)
T5 = (5, 5, 1, 5, 0)
Selection of edges according to minimum distance are:
V1 -> V2 = 4
V2 -> V4 = 2
V4 -> V3 = 2
V3 -> V5 = 1
Thus, MST is V1 -> V2 -> V4 -> V3 -> V5 and the distance travelled is 9 (4+2+2+1)
Literally,I don't have idea about how to create a graph of n vertices in R.
I searched in google but i didn't understand how to approach above problem.
Please,help me.
igraph
package, or this question or this function? – Sarenaadj = rbind(T1, T2, T3, T4, T5)
, then read intoigraph
:g = graph_from_adjacency_matrix(adj, weighted = TRUE)
. Then you can calculate themst
– MiddlebrooksT1, T2,T3,T4,T5
are distances from vertices . How can i know those distances before .First , I have to create graph right? – NinnetteDistance between the edges of the vertices
means distance between the vertices. – NinnetteT1 <- c(0,4,5,7,5) > T2 = c(4, 0, 6, 2, 5) > T3 = c(5, 6, 0, 2, 1) > T4 = c(7, 2, 2, 0, 5) > T5 = c(5, 5, 1, 5, 0) > adj = rbind(T1, T2, T3, T4, T5) > g = graph_from_adjacency_matrix(adj, weighted = TRUE) > z<-mst(g, weights = TRUE) Error in mst(g, weights = TRUE) : At spanning_trees.c:287 : Invalid weights length, Invalid value
– Ninnettemst(g)
but perhaps alsomst(g, weights = E(g)$weights)
? – Middlebrooksadj
above represents the code in your question and a weighted graph?. Each row/column gives the connection to the other nodes in the graph. If there was a zero in the adj matrix then there would be no edge. You often see these as unweighted adjacency matrices with only ones or zeros indicating an edge or not. As you are given weights (the distance between each edge) these are used in the adj matrix instead of ones to indicate the edge. – Middlebrooksz IGRAPH f716a5f D-W- 5 4 -- + attr: weight (e/n) + edges from f716a5f: [1] 2->1 3->4 4->2 5->3
.Thank you. – Ninnettesum(E(mg)$weight)
, wheremg
is the minimum spanning tree graph – Middlebrooks