README
¶
Your basic graph 
Golang library of basic graph algorithms
Topological ordering, image by David Eppstein, CC0 1.0.
This library offers efficient and well-tested algorithms for
- breadth-first and depth-first search,
- topological ordering,
- strongly and weakly connected components,
- bipartion,
- shortest paths,
- maximum flow,
- Euler walks,
- and minimum spanning trees.
The algorithms can be applied to any graph data structure implementing
the two Iterator
methods: Order
, which returns the number of vertices,
and Visit
, which iterates over the neighbors of a vertex.
All algorithms operate on directed graphs with a fixed number of vertices, labeled from 0 to n-1, and edges with integer cost. An undirected edge {v, w} of cost c is represented by the two directed edges (v, w) and (w, v), both of cost c. A self-loop, an edge connecting a vertex to itself, is both directed and undirected.
Graph data structures
The type Mutable
represents a directed graph with a fixed number
of vertices and weighted edges that can be added or removed.
The implementation uses hash maps to associate each vertex
in the graph with its adjacent vertices. This gives constant
time performance for all basic operations.
The type Immutable
is a compact representation of an immutable graph.
The implementation uses lists to associate each vertex in the graph
with its adjacent vertices. This makes for fast and predictable
iteration: the Visit method produces its elements by reading
from a fixed sorted precomputed list.
Virtual graphs
The subpackage graph/build
offers a tool for building graphs of type Virtual
.
In a virtual graph no vertices or edges are stored in memory, they are instead computed as needed. New virtual graphs are constructed by composing and filtering a set of standard graphs, or by writing functions that describe the edges of a graph.
The following standard graphs are predefined:
- empty graphs,
- complete graphs and complete bipartite graphs,
- grid graphs and complete k-ary trees,
- cycle graphs and circulant graphs,
- and hypergraphs.
The following operations are supported:
- adding and deleting sets of edges,
- adding cost functions,
- filtering graphs by edge functions,
- complement, intersection and union,
- subgraphs,
- connecting graphs at a single vertex,
- joining two graphs by a set of edges,
- matching two graphs by a set of edges,
- cartesian product and tensor product.
Non-virtual graphs can be imported, and used as building blocks,
by the Specific
function. Virtual graphs don't need to be “exported”;
they implement the Iterator
interface and hence can be used directly
by any algorithm in the graph package.
Installation
Once you have installed Go, run this command
to install the graph
package:
go get github.com/yourbasic/graph
Documentation
There is an online reference for the package at godoc.org/github.com/yourbasic/graph.
Roadmap
- The API of this library is frozen.
- Bug fixes and performance enhancement can be expected.
- New functionality might be included.
- Version numbers adhere to semantic versioning.
The only accepted reason to modify the API of this package is to handle issues that can't be resolved in any other reasonable way.
New features and performance enhancements are limited to basic algorithms and data structures, akin to the ones that you might find in a computer science textbook.
Stefan Nilsson – korthaj
Documentation
¶
Overview ¶
Package graph contains generic implementations of basic graph algorithms.
Generic graph algorithms ¶
The algorithms in this library can be applied to any graph data structure implementing the two Iterator methods: Order, which returns the number of vertices, and Visit, which iterates over the neighbors of a vertex.
All algorithms operate on directed graphs with a fixed number of vertices, labeled from 0 to n-1, and edges with integer cost. An undirected edge {v, w} of cost c is represented by the two directed edges (v, w) and (w, v), both of cost c. A self-loop, an edge connecting a vertex to itself, is both directed and undirected.
Graph data structures ¶
The type Mutable represents a directed graph with a fixed number of vertices and weighted edges that can be added or removed. The implementation uses hash maps to associate each vertex in the graph with its adjacent vertices. This gives constant time performance for all basic operations.
The type Immutable is a compact representation of an immutable graph. The implementation uses lists to associate each vertex in the graph with its adjacent vertices. This makes for fast and predictable iteration: the Visit method produces its elements by reading from a fixed sorted precomputed list. This type supports multigraphs.
Virtual graphs ¶
The subpackage graph/build offers a tool for building virtual graphs. In a virtual graph no vertices or edges are stored in memory, they are instead computed as needed. New virtual graphs are constructed by composing and filtering a set of standard graphs, or by writing functions that describe the edges of a graph.
Tutorial ¶
The Basics example shows how to build a plain graph and how to efficiently use the Visit iterator, the key abstraction of this package.
The DFS example contains a full implementation of depth-first search.
Example (DFS) ¶
Show how to use this package by implementing a complete depth-first search.
Output: 4 [(0 1) {1 2}] {8 [2 2 2 2] [-1 0 1 -1] [1 2 3 7] [6 5 4 8]}
Index ¶
- Constants
- func Acyclic(g Iterator) bool
- func BFS(g Iterator, v int, do func(v, w int, c int64))
- func Bipartition(g Iterator) (part []int, ok bool)
- func Components(g Iterator) [][]int
- func Connected(g Iterator) bool
- func Equal(g, h Iterator) bool
- func EulerDirected(g Iterator) (walk []int, ok bool)
- func EulerUndirected(g Iterator) (walk []int, ok bool)
- func MST(g Iterator) (parent []int)
- func ShortestPath(g Iterator, v, w int) (path []int, dist int64)
- func ShortestPaths(g Iterator, v int) (parent []int, dist []int64)
- func String(g Iterator) string
- func StrongComponents(g Iterator) [][]int
- func TopSort(g Iterator) (order []int, ok bool)
- type Immutable
- type Iterator
- type Mutable
- func (g *Mutable) Add(v, w int)
- func (g *Mutable) AddBoth(v, w int)
- func (g *Mutable) AddBothCost(v, w int, c int64)
- func (g *Mutable) AddCost(v, w int, c int64)
- func (g *Mutable) Cost(v, w int) int64
- func (g *Mutable) Degree(v int) int
- func (g *Mutable) Delete(v, w int)
- func (g *Mutable) DeleteBoth(v, w int)
- func (g *Mutable) Edge(v, w int) bool
- func (g *Mutable) Order() int
- func (g *Mutable) String() string
- func (g *Mutable) Visit(v int, do func(w int, c int64) bool) bool
- type Stats
Examples ¶
Constants ¶
const ( Max int64 = 1<<63 - 1 Min int64 = -1 << 63 )
The maximum and minimum value of an edge cost.
Variables ¶
This section is empty.
Functions ¶
func BFS ¶
BFS traverses g in breadth-first order starting at v. When the algorithm follows an edge (v, w) and finds a previously unvisited vertex w, it calls do(v, w, c) with c equal to the cost of the edge (v, w).
Example ¶
Find the shortest distances from a vertex in an unweighted graph.
Output: 0 to 1 0 to 3 1 to 2 1 to 4 2 to 5 dist: [0 1 2 1 2 3]
func Bipartition ¶
Bipartition returns a subset U of g's vertices with the property that every edge of g connects a vertex in U to one outside of U. If g isn't bipartite, it returns an empty slice and sets ok to false.
func Components ¶
Components produces a partition of g's vertices into its (weakly) connected components.
func Equal ¶
Equal tells if g and h have the same number of vertices, and the same edges with the same costs.
func EulerDirected ¶
EulerDirected returns an Euler walk in a directed graph. If no such walk exists, it returns an empty walk and sets ok to false.
func EulerUndirected ¶
EulerUndirected returns an Euler walk following undirected edges in only one direction. If no such walk exists, it returns an empty walk and sets ok to false.
func MST ¶
MST computes a minimum spanning tree for each connected component of an undirected weighted graph. The forest of spanning trees is returned as a slice of parent pointers: parent[v] is either the parent of v in a tree, or -1 if v is the root of a tree.
The time complexity is O(|E|⋅log|V|), where |E| is the number of edges and |V| the number of vertices in the graph.
func ShortestPath ¶
ShortestPath computes a shortest path from v to w. Only edges with non-negative costs are included. The number dist is the length of the path, or -1 if w cannot be reached.
The time complexity is O((|E| + |V|)⋅log|V|), where |E| is the number of edges and |V| the number of vertices in the graph.
Example ¶
Find a shortest path between two vertices in a graph.
Output: path: [0 3 4 1 2 5] length: 10
func ShortestPaths ¶
ShortestPaths computes the shortest paths from v to all other vertices. Only edges with non-negative costs are included. The number parent[w] is the predecessor of w on a shortest path from v to w, or -1 if none exists. The number dist[w] equals the length of a shortest path from v to w, or is -1 if w cannot be reached.
The time complexity is O((|E| + |V|)⋅log|V|), where |E| is the number of edges and |V| the number of vertices in the graph.
func String ¶
String returns a description of g with two elements: the number of vertices, followed by a sorted list of all edges.
func StrongComponents ¶
StrongComponents produces a partition of g's vertices into its strongly connected components.
A component is strongly connected if all its vertices are reachable from every other vertex in the component. Each vertex of the graph appears in exactly one of the strongly connected components, and any vertex that is not on a directed cycle forms a strongly connected component all by itself.
Types ¶
type Immutable ¶
type Immutable struct {
// contains filtered or unexported fields
}
Immutable is a compact representation of an immutable graph. The implementation uses lists to associate each vertex in the graph with its adjacent vertices. This makes for fast and predictable iteration: the Visit method produces its elements by reading from a fixed sorted precomputed list. This type supports multigraphs.
func Sort ¶
Sort returns an immutable copy of g with a Visit method that returns its neighbors in increasing numerical order.
func Transpose ¶
Transpose returns the transpose graph of g. The transpose graph has the same set of vertices as g, but all of the edges are reversed compared to the orientation of the corresponding edges in g.
func (*Immutable) Visit ¶
Visit calls the do function for each neighbor w of v, with c equal to the cost of the edge from v to w. The neighbors are visited in increasing numerical order. If do returns true, Visit returns immediately, skipping any remaining neighbors, and returns true.
func (*Immutable) VisitFrom ¶
VisitFrom calls the do function starting from the first neighbor w for which w ≥ a, with c equal to the cost of the edge from v to w. The neighbors are then visited in increasing numerical order. If do returns true, VisitFrom returns immediately, skipping any remaining neighbors, and returns true.
type Iterator ¶
type Iterator interface { // Order returns the number of vertices in a graph. Order() int // Visit calls the do function for each neighbor w of vertex v, // with c equal to the cost of the edge from v to w. // // • If do returns true, Visit returns immediately, skipping // any remaining neighbors, and returns true. // // • The calls to the do function may occur in any order, // and the order may vary. // Visit(v int, do func(w int, c int64) (skip bool)) (aborted bool) }
Iterator describes a weighted graph; an Iterator can be used to describe both ordinary graphs and multigraphs.
type Mutable ¶
type Mutable struct {
// contains filtered or unexported fields
}
Mutable represents a directed graph with a fixed number of vertices and weighted edges that can be added or removed. The implementation uses hash maps to associate each vertex in the graph with its adjacent vertices. This gives constant time performance for all basic operations.
func (*Mutable) Add ¶
Add inserts a directed edge from v to w with zero cost. It removes the previous cost if this edge already exists.
func (*Mutable) AddBoth ¶
AddBoth inserts edges with zero cost between v and w. It removes the previous costs if these edges already exist.
func (*Mutable) AddBothCost ¶
AddBothCost inserts edges with cost c between v and w. It overwrites the previous costs if these edges already exist.
func (*Mutable) AddCost ¶
AddCost inserts a directed edge from v to w with cost c. It overwrites the previous cost if this edge already exists.
func (*Mutable) DeleteBoth ¶
DeleteBoth removes all edges between v and w.
func (*Mutable) Visit ¶
Visit calls the do function for each neighbor w of v, with c equal to the cost of the edge from v to w. If do returns true, Visit returns immediately, skipping any remaining neighbors, and returns true.
The iteration order is not specified and is not guaranteed to be the same every time. It is safe to delete, but not to add, edges adjacent to v during a call to this method.