简体   繁体   中英

Minimum spanning tree in python

I'm having problems calculating the minimum spanning tree of a simple graph using the following python snippet. It is trivial to do it by hand and I've included an image of the graph and the minimum spanning tree from the textbook.

import numpy as np
import pandas as pd
import scipy as sp
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import minimum_spanning_tree

import networkx as nx
import matplotlib.pyplot as plt
%matplotlib inline
friendships = [
    ('A', 'B',{'weight':2}),
    ('A', 'E',{'weight':10}),
    ('A', 'D',{'weight':1}),
    ('A', 'C',{'weight':4}),
    ('B', 'D',{'weight':1}),
    ('C', 'D',{'weight':4}),
    ('D', 'E',{'weight':7}),
    ('D', 'F',{'weight':10}),
    ('E', 'F',{'weight':8}),
    ('D', 'G',{'weight':7}),
    ('C', 'G',{'weight':3}),
    ('E', 'G',{'weight':5}),

]

G = nx.MultiGraph()
G.add_edges_from(friendships)
X = nx.to_numpy_matrix(G)
nx.draw(G, with_labels=True, font_weight='bold')

X = csr_matrix(X)
Tcsr = minimum_spanning_tree(X)
Tcsr.toarray().astype(int)

If you run the code, you get "ABGFECD". More like a list.

Visually, the graph and the answer from the book are the following:

Original_Graph

MST

A minimum spanning tree is a subset of the edges of the original graph, so "ABGFECD" cannot be a solution (unless the solution is a path). You are missing the edge (F, G) in the friendships list. Now you will obtain:

  (0, 3)    1.0
  (0, 4)    4.0
  (1, 3)    1.0
  (2, 6)    5.0
  (4, 6)    3.0
  (5, 6)    3.0

and following the order of the nodes in the friendships adjacency list, this is equivalent to:

  (A, D)    1.0
  (A, C)    4.0
  (B, D)    1.0
  (E, G)    5.0
  (C, G)    3.0
  (F, G)    3.0

Note that, the minimum spanning tree of a graph is not unique. Rather than checking the edges of the obtained tree, you need to check that the weight of the tree is the same as in the example of the book, ie, 17.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM