NEP -DAA -DESIGN AND ANALYSIS OF ALOGRITHM

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5 PROGRAM 6 PROGRAM 7 PROGRAM 8 PROGRAM 9 PROGRAM 10 PROGRAM 11 PROGRAM 12

PART B

PROGRAM B1 PROGRAM B2 PROGRAM B3 PROGRAM B4 PROGRAM B5 PROGRAM B6 PROGRAM B7 PROGRAM B8 . . .

 
     
 # Function to find the Minimum Spanning Tree using Kruskal's algorithm
kruskal_mst <- function(graph) {
  num_vertices <- nrow(graph)
  
  # Create a list to store the MST edges
  mst_edges <- list()
  
  # Create a vector to track the parent of each vertex in a forest
  parent <- 1:num_vertices
  
  # Helper function to find the root of a set (connected component)
  find_root <- function(x) {
    if (x != parent[x]) {
      parent[x] <- find_root(parent[x])
    }
    return(parent[x])
  }
  
  # Sort the edges by weight
  edges <- data.frame(
    from = rep(1:num_vertices, each = num_vertices),
    to = rep(1:num_vertices, times = num_vertices),
    weight = as.vector(graph)
  )
  edges <- edges[order(edges$weight), ]
  
  # Iterate through sorted edges
  for (i in 1:(num_vertices - 1)) {
    edge <- edges[i, ]
    root_from <- find_root(edge$from)
    root_to <- find_root(edge$to)
    
    # If adding the edge doesn't create a cycle, include it in the MST
    if (root_from != root_to) {
      mst_edges <- c(mst_edges, list(edge))
      parent[root_from] <- root_to
    }
  }
  
  return(mst_edges)
}

# Example usage
# Create an adjacency matrix representing a graph (replace this with your own graph)
graph <- matrix(c(
  0, 2, 0, 6, 0,
  2, 0, 3, 8, 5,
  0, 3, 0, 0, 7,
  6, 8, 0, 0, 9,
  0, 5, 7, 9, 0
), nrow = 5)

mst <- kruskal_mst(graph)

cat("Minimum Spanning Tree Edges:\n")
for (edge in mst) {
  cat("From: ", edge$from, " To: ", edge$to, " Weight: ", edge$weight, "\n")
}