问题
Hey guys i need to output the girth of a given graph represented as an adjacency matrix.Could anyone give me some hints how i can use an adjacency matrix or an adjacency list to obtain the girth of a graph ? Thanks
Example:
graph one:
0 1 0 0
1 0 0 1
0 0 0 0
0 1 0 0
graph two:
0 1 0 0 1
1 0 1 0 0
0 1 0 1 0
0 0 1 0 1
1 0 0 1 0
The result:
Girth of graph 1: infinity
Girth of graph 2: 5
回答1:
This algorithm will find the length of the shortest cycle:
- set `girth` to infinity
- for each edge
-- remove the edge from the graph
-- measure the distance between the edge endpoints
-- if `girth` is longer than distance+1
--- set `girth` to distance+1
-- return the edge to the graph.
The time complexity is of the Dijkstra's algorithm is O(v^2)
, so this algorithm is O(v^4)
.
If your graph is sparse, you can convert to a neighbor-list representation and then run the previous algorithm in O(v^2+e*(e+v*log(v)))
=O(v^2+e^2+v*e*log(v))
回答2:
There is an algorithm at http://webcourse.cs.technion.ac.il/234247/Winter2003-2004/ho/WCFiles/Girth.pdf based on BFS, with complexity O(VE). This is for undirected graphs (e.g., your example adjaceny matrices are symmetric). See also https://github.com/jaspervdj/Genus/blob/master/src/genus/FindGirth.java.
回答3:
It's cheaper(O(v^3)) if you run dijkstra from all points and take each round the maximum distance from that given source. Then take the maximum of these elements and that's the girth.
回答4:
Girth of a graph is the length of the shortest cycle contained in a graph i.e. a cycle with the least possible sum( can be negative , if graph has a negative cycle). The easiest way to find girth is to run Floyd Warshall algorithm( in O(V^3) time ) on the given graph( having V<= 400) and storing the distance between every pair in 2-D array. After that iterate over the dist[i][i] for every possible vertex( in O(V) time ) , to check if there exist a cycle that start with vertex i and end at vertex i, and then take the minimum of all possible values obtained from dist[i][i].
回答5:
In Sage
sage: G1 = Matrix([[0,1,0,0],[1,0,0,1],[0,0,0,0],[0,1,0,0]])
sage: G2 = Matrix([[0,1,0,0,1],[1,0,1,0,0],[0,1,0,1,0],[0,0,1,0,1],[1,0,0,1,0]])
sage: G1 = Graph(G1)
sage: G2 = Graph(G2)
sage: G1.girth()
+Infinity
sage: G2.girth()
5
来源:https://stackoverflow.com/questions/12890106/find-the-girth-of-a-graph