This project is read-only.

Creating Graphs

Easy creation with extension methods
QuickGraph provides several extension methods in QuickGraph.GraphExtensions to create graph from list of edge or vertices. For example, from an IEnumerable<Edge<int>>:
using QuickGraph; // enables extension methods

var edges = new SEdge<int>[] { new SEdge<int>(1,2), new SEdge<int>(0,1) };
var graph = edges.ToAdjacencyGraph<int, SEdge<int>>(edges);

Create a graph instance
Let us assume we need integer vertices and edges tagged with string. Int is the vertex type and we can use the MarkedEdge generic type for the edge type:
  • TVertex type: int
  • TEdge type using TaggedEdge<Vertex,Marker>: TaggedEdge<int, string>
var g = new AdjacencyGraph<int, TaggedEdge<int, string>>();

Wrapping a dictionary into a graph
You may have already a dictionary on hand that represents a graph, where the keys are the vertices and the value is a collection of out-edges (or adjacent edges). You can wrap this dictionary with QuickGraph without re-allocating new memory:
Dictionary<int, int[]> dic = ...; // vertex -> target edges
var graph = dic.ToVertexAndEdgeListGraph(
    kv => Array.ConvertAll(kv.Value, v => new SEquatableEdge<int>(kv.Key, v))

-- without extension methods
var graph = GraphExtensions.ToVertexAndEdgeListGraph(
    kv => Array.ConvertAll(kv.Value, v => new SEquatableEdge<int>(kv.Key, v))

Adding vertices
This snippet creates two vertices and adds them to the graph.
int v1 = 1;
int v2 = 2;

Adding edges
The edges (v1,v2) and (v2,v1) are created and added to the graph.
var e1 = new TaggedEdge<int,string>(v1,v2,”hello”);

Adding edges (and vertices)
You can also add an edge and implicitely add the vertices if they are missing
// v3, v4 are not added to the graph yet
var e2 = new TaggedEdge<int,string>(v3,v4,”hello”);


Last edited Aug 27, 2009 at 6:00 PM by pelikhan, version 17


hmv Apr 29, 2016 at 7:42 PM 
I intended to assign weights to the edges but couldn't see any hints on how to do it. All examples I saw used strings as tags, so I went out looking for discussions on the subject. I found several references to it, with helper dictionaries being apparently the most used alternative.
However, looking at the definition of TaggedEdge, TTag could be anything, so I created a class with a few properties and everything seems to work fine. I just have to cast the tag when reading it, and my problem seems to be solved.
So, I wonder why I couldn't find any references about using user-defined types instead of strings... Is there any particular reason not to do it ?

libdab Jul 5, 2014 at 10:21 AM 
Thanks for this - some really useful methods there. Could you edit the first example as suggested above?

jbuedel Jan 7, 2011 at 10:07 PM 
There's a bug in the first example. No param needs to be passed to ToAdjacencyGraph(), but if one is, it should be a bool.