Skip to content

Creating Graphs

Alexandre Rabérin edited this page Oct 28, 2020 · 2 revisions

Creating Graphs

Easy creation with extension methods

QuikGraph provides several extension methods in QuikGraph.GraphExtensions to create graph from list of edge or vertices. For example, from an IEnumerable<Edge<int>>:

using QuikGraph; // enables extension methods

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

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 TaggedEdge<TVertex, TTag> generic type for the edge type:

  • TVertex is int
  • TEdge type using TaggedEdge<Vertex, Marker>: TaggedEdge<int, string>
var graph = 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 QuikGraph without re-allocating new memory:

Dictionary<int, int[]> dictionary = ...; // Vertex -> Target edges
var graph = dictionary.ToDelegateVertexAndEdgeListGraph(
    kv => Array.ConvertAll(kv.Value, v => new Edge<int>(kv.Key, v)));

// Without extension method
var graph = GraphExtensions.ToDelegateVertexAndEdgeListGraph(
    dictionary,
    kv => Array.ConvertAll(kv.Value, v => new Edge<int>(kv.Key, v)));

Adding vertices

This snippet creates two vertices and adds them to the graph.

int vertex1 = 1;
int vertex2 = 2;

graph.AddVertex(vertex1);
graph.AddVertex(vertex2);

Adding edges

Adds an edge to the graph. Note that vertices vertex1 and vertex2 are already added to the graph beforehand.

var edge1 = new TaggedEdge<int, string>(vertex1, vertex2, "hello");

graph.AddEdge(edge1); 

For more details about QuikGraph built-in edge objects you can consult the Edges page.

Adding edges (and vertices)

You can also add an edge and implicitly add the vertices if they are missing.

// vertex3, vertex4 are not added into the graph yet
var edge2 = new TaggedEdge<int, string>(vertex3, vertex4, "hello");

graph.AddVerticesAndEdge(edge2);

Vertex and edge ranges

It is also possible to add a batch of vertices (same for edges) in one operation.

// Vertex range
graph.AddVertexRange(new[] { vertex5, vertex6 });

// Edge range
graph.AddEdgeRange(new[] { edge3, edge4 });

// Edge range (and implicitly vertices)
graph.AddVerticesAndEdgeRange(new[] { edge5, edge6 });
Clone this wiki locally