# Ticket #7184: trac_7184.patch

File trac_7184.patch, 3.6 KB (added by AJonsson, 11 years ago)

count spanning trees of graphs

• ## sage/graphs/graph.py

```# HG changeset patch
# User Anders Jonsson <anders.jonsson@norsjonet.se>
# Date 1255196120 -7200
# Node ID 2bc5e73a048f6b25cda72382bc6b8dc7bc67ede9
# Parent  9fd37b2248850bca9f9492d1be97f02c3025621a
Implement counting of spanning trees of graphs and digraphs

diff -r 9fd37b224885 -r 2bc5e73a048f sage/graphs/graph.py```
 a -  Stephen Hartke (2009-07-26): Fixed bug in blocks_and_cut_vertices() that caused an incorrect result when the vertex 0 was a cut vertex. -  Anders Jonsson (2009-10-10): Counting of spanning trees added. Graph Format num_edges = size def spanning_trees(self, root_vertex=0): """ Returns the number of spanning trees in a graph. In the case of a digraph, use vertex number of the desired root vertex as argument. Default is to set first vertex as root. This computation uses Kirchhoff's Matrix Tree Theorem [1] to calculate the number of spanning trees. For complete graphs on n vertices the result can also be reached using Cayley's formula: the number of spanning trees are n^(n-2). For digraphs, the augmented Kirchhoff Matrix as defined in [2] is used for calculations. Here the result is the number of out-trees rooted at a specific vertex. INPUT: - ``root_vertex`` - integer (default: 0, or the number of the first vertex if vertex 0 not is in the graph) This is the vertex that will be used as root for all spanning trees if the graph is a directed graph. REFERENCES: - [1] http://mathworld.wolfram.com/MatrixTreeTheorem.html - [2] Lih-Hsing Hsu, Cheng-Kuan Lin, "Graph Theory and Interconnection Networks" AUTHORS: - Anders Jonsson (2009-10-10) EXAMPLES:: sage: G = graphs.PetersenGraph() sage: G.spanning_trees() 2000 :: sage: n = 11 sage: G = graphs.CompleteGraph(n) sage: ST = G.spanning_trees() sage: ST == n^(n-2) True :: sage: M=matrix(3,3,[0,1,0,0,0,1,1,1,0]) sage: D=DiGraph(M) sage: D.spanning_trees() 1 sage: D.spanning_trees(0) 1 sage: D.spanning_trees(2) 2 """ if self.is_directed() == False: M=self.kirchhoff_matrix() M.subdivide(1,1) M2 = M.subdivision(1,1) return abs(M2.determinant()) else: G=self.copy() n = G.vertices()[G.order()-1] + 1 if root_vertex == 0: root_vertex=G.vertices()[0] if root_vertex not in G.vertices(): raise RuntimeError("Vertex (%s) not in the graph."%root_vertex) G.add_vertex(n) G.add_edge(n,root_vertex) M=G.kirchhoff_matrix() j=0 for i in G.vertices(): M[j,j]=G.in_degree(i) j= j + 1 M.subdivide(G.order()-1,G.order()-1) M2=M.subdivision(0,0) return abs(M2.determinant()) ### Planarity def is_planar(self, on_embedding=None, kuratowski=False, set_embedding=False, set_pos=False):