QuickGraph.NETStandard
4.0.0
dotnet add package QuickGraph.NETStandard --version 4.0.0
NuGet\Install-Package QuickGraph.NETStandard -Version 4.0.0
<PackageReference Include="QuickGraph.NETStandard" Version="4.0.0" />
<PackageVersion Include="QuickGraph.NETStandard" Version="4.0.0" />
<PackageReference Include="QuickGraph.NETStandard" />
paket add QuickGraph.NETStandard --version 4.0.0
#r "nuget: QuickGraph.NETStandard, 4.0.0"
#:package QuickGraph.NETStandard@4.0.0
#addin nuget:?package=QuickGraph.NETStandard&version=4.0.0
#tool nuget:?package=QuickGraph.NETStandard&version=4.0.0
QuickGraph.NETStandard Examples
A comprehensive collection of examples demonstrating the capabilities of the QuickGraph.NETStandard library.
Overview
QuickGraph.NETStandard is a powerful graph data structure and algorithm library for .NET. These examples showcase various graph types, algorithms, visualization techniques, and real-world applications.
Prerequisites
- .NET 10 or later (for Examples project)
- .NET Standard 2.1 (for QuickGraph.NETStandard library)
- Optional: Graphviz for graph visualization
Installing Graphviz
To use the visualization features, install Graphviz:
Windows:
- Download from https://graphviz.org/download/
- Run installer and add to PATH
- Restart your IDE
Linux:
sudo apt-get install graphviz # Ubuntu/Debian
sudo yum install graphviz # Fedora/RHEL
macOS:
brew install graphviz
Running the Examples
cd Examples
dotnet run
A menu-driven interface will guide you through all available examples.
Example Categories
1. Basic Graphs (Examples 1-4)
Learn fundamental graph data structures:
Example 1: Simple Directed Graph
- Concepts: Directed edges, vertex/edge addition, adjacency queries
- Use Case: One-way relationships (web links, citations, task dependencies)
- Key Methods:
AddVertex(),AddEdge(),OutEdges(),InDegree()
Example 2: Undirected Graph
- Concepts: Bidirectional edges, symmetric relationships
- Use Case: Friendships, road networks, physical connections
- Key Methods:
AdjacentEdges(),AdjacentDegree(), connectivity checks
Example 3: Bidirectional Graph
- Concepts: Directed graph with efficient reverse edge lookup
- Use Case: Web page navigation, dependency analysis
- Key Methods:
OutEdges(),InEdges(), degree centrality
Example 4: Custom Edge Types
- Concepts: Edges with properties (weight, cost, capacity, labels)
- Use Case: Weighted graphs, cost optimization, flow networks
- Features: Custom edge classes with domain-specific data
2. Graph Algorithms (Examples 5-12)
Master essential graph algorithms:
Example 5: Shortest Path (Dijkstra)
- Algorithm: Dijkstra's shortest path
- Complexity: O((V + E) log V)
- Use Case: GPS navigation, network routing, delivery optimization
- Features: Weighted edges, path reconstruction, distance calculation
Example 6: Breadth-First Search (BFS)
- Algorithm: Level-order traversal
- Complexity: O(V + E)
- Use Case: Shortest path in unweighted graphs, level detection, web crawling
- Features: Discovery order, tree edges, level-by-level exploration
Example 7: Depth-First Search (DFS)
- Algorithm: Deep-first traversal with backtracking
- Complexity: O(V + E)
- Use Case: Cycle detection, pathfinding, maze solving
- Features: Discovery/finish times, tree/back edges, parenthesis theorem
Example 8: Topological Sort
- Algorithm: Dependency-ordered traversal
- Complexity: O(V + E)
- Use Case: Build systems, task scheduling, course prerequisites
- Features: DAG validation, parallel execution levels, cycle detection
- Note: Only works on Directed Acyclic Graphs (DAGs)
Example 9: Strongly Connected Components
- Algorithm: Tarjan's or Kosaraju's algorithm
- Complexity: O(V + E)
- Use Case: Community detection, circuit analysis, web page clustering
- Features: Component identification, reachability analysis
Example 10: Minimum Spanning Tree (Kruskal)
- Algorithm: Kruskal's MST with Union-Find
- Complexity: O(E log V)
- Use Case: Network design, cable routing, cost minimization
- Features: Minimum cost connectivity, forest to tree conversion
Example 11: Maximum Flow (Edmonds-Karp)
- Algorithm: Ford-Fulkerson with BFS
- Complexity: O(V � E�)
- Use Case: Network capacity, supply chain, bandwidth allocation
- Features: Flow distribution, bottleneck identification, residual networks
Example 12: Cycle Detection
- Algorithm: DFS-based back edge detection
- Complexity: O(V + E)
- Use Case: Deadlock detection, circular dependency resolution
- Features: Directed/undirected cycle detection, cycle path reconstruction
3. Visualization (Examples 13-15)
Create professional graph visualizations:
Example 13: Basic Visualization
- Format: DOT language (Graphviz)
- Outputs: PNG, SVG, PDF, etc.
- Features: Automatic layout, DOT file generation
- Tools: Integrates with Graphviz
Example 14: Styled Visualization
- Customization: Colors, shapes, labels, styles
- Features: Vertex formatting, edge styling, conditional formatting
- Use Case: State machines, workflow diagrams, network maps
Example 15: Hierarchical Layout
- Layouts: Top-to-bottom, left-to-right, etc.
- Use Case: Organizational charts, tree structures, class hierarchies
- Features: Rank direction, level-based coloring, shape differentiation
4. Real-World Scenarios (Examples 16-19)
Apply graph theory to practical problems:
Example 16: Social Network Analysis
- Features:
- Influencer identification (degree centrality)
- Community detection
- Mutual friend discovery
- Connection recommendations
- Algorithms: Degree centrality, path analysis
- Metrics: Network density, clustering coefficient
Example 17: Route Planning (GPS/Maps)
- Features:
- Multi-criteria optimization (distance, time, cost)
- Alternative route suggestions
- Road type preferences
- Real-time routing
- Algorithms: Dijkstra with custom cost functions
- Use Case: Navigation apps, delivery routing, trip planning
Example 18: Task Dependency Management
- Features:
- Critical path analysis
- Project duration calculation
- Resource allocation
- Parallel execution detection
- Algorithms: Topological sort, forward/backward pass
- Use Case: Project management, build systems, CI/CD pipelines
Example 19: Network Topology Analysis
- Features:
- Redundancy checking
- Single point of failure detection
- Bandwidth capacity analysis
- Failover simulation
- Algorithms: Multiple path finding, connectivity testing
- Use Case: Infrastructure planning, disaster recovery, network design
Code Structure
Examples/
??? Program.cs # Main menu application
??? BasicGraphs/
? ??? SimpleDirectedGraphExample.cs
? ??? UndirectedGraphExample.cs
? ??? BidirectionalGraphExample.cs
? ??? CustomEdgeTypesExample.cs
??? Algorithms/
? ??? ShortestPathExample.cs
? ??? BreadthFirstSearchExample.cs
? ??? DepthFirstSearchExample.cs
? ??? TopologicalSortExample.cs
? ??? StronglyConnectedComponentsExample.cs
? ??? MinimumSpanningTreeExample.cs
? ??? MaximumFlowExample.cs
? ??? CycleDetectionExample.cs
??? Visualization/
? ??? BasicVisualizationExample.cs
? ??? StyledVisualizationExample.cs
? ??? HierarchicalLayoutExample.cs
??? RealWorldScenarios/
??? SocialNetworkExample.cs
??? RoutePlanningExample.cs
??? TaskDependencyExample.cs
??? NetworkTopologyExample.cs
Key Concepts
Graph Types
| Type | Description | When to Use |
|---|---|---|
AdjacencyGraph<TVertex, TEdge> |
Directed graph | One-way relationships, dependencies |
UndirectedGraph<TVertex, TEdge> |
Undirected graph | Symmetric relationships, networks |
BidirectionalGraph<TVertex, TEdge> |
Directed with reverse lookup | Need both in/out edges efficiently |
Common Operations
// Create graph
var graph = new AdjacencyGraph<string, Edge<string>>();
// Add vertices
graph.AddVertex("A");
graph.AddVertexRange(new[] { "B", "C", "D" });
// Add edges
graph.AddEdge(new Edge<string>("A", "B"));
graph.AddVerticesAndEdge(new Edge<string>("B", "C")); // Adds vertices if needed
// Query
int vertexCount = graph.VertexCount;
int edgeCount = graph.EdgeCount;
bool hasEdge = graph.ContainsEdge("A", "B");
int outDegree = graph.OutDegree("A");
IEnumerable<Edge<string>> edges = graph.OutEdges("A");
// Algorithms
var shortestPath = graph.ShortestPathsDijkstra(costFunc, "start");
var topologicalOrder = graph.TopologicalSort();
var components = graph.StronglyConnectedComponents(out var componentMap);
Custom Edge Types
public class WeightedEdge : Edge<string>
{
public double Weight { get; set; }
public WeightedEdge(string source, string target, double weight)
: base(source, target)
{
Weight = weight;
}
}
var graph = new AdjacencyGraph<string, WeightedEdge>();
graph.AddVerticesAndEdge(new WeightedEdge("A", "B", 5.0));
Performance Characteristics
| Algorithm | Time Complexity | Space Complexity |
|---|---|---|
| BFS | O(V + E) | O(V) |
| DFS | O(V + E) | O(V) |
| Dijkstra | O((V + E) log V) | O(V) |
| Topological Sort | O(V + E) | O(V) |
| Kruskal's MST | O(E log V) | O(V) |
| Edmonds-Karp | O(V � E�) | O(V + E) |
| Strongly Connected Components | O(V + E) | O(V) |
Visualization Output
All visualization examples create two files:
.dotfile - Text format that can be edited or processed.pngfile - Visual representation (requires Graphviz)
Without Graphviz: Copy the DOT content to https://dreampuf.github.io/GraphvizOnline/
Common Patterns
Pattern 1: Weighted Shortest Path
var graph = new AdjacencyGraph<string, Edge<string>>();
var weights = new Dictionary<Edge<string>, double>();
// Add weighted edges
void AddWeightedEdge(string from, string to, double weight) {
var edge = new Edge<string>(from, to);
graph.AddVerticesAndEdge(edge);
weights[edge] = weight;
}
// Find shortest path
Func<Edge<string>, double> costFunc = e => weights[e];
var tryGetPath = graph.ShortestPathsDijkstra(costFunc, "start");
if (tryGetPath("end", out var path)) {
// Process path
}
Pattern 2: Graph Traversal with State
var visited = new HashSet<string>();
var dfs = new DepthFirstSearchAlgorithm<string, Edge<string>>(graph);
dfs.DiscoverVertex += vertex => {
visited.Add(vertex);
Console.WriteLine($"Discovered: {vertex}");
};
dfs.FinishVertex += vertex => {
Console.WriteLine($"Finished: {vertex}");
};
dfs.Compute("start");
Pattern 3: Custom Visualization
var viz = new GraphvizAlgorithm<string, Edge<string>>(graph);
viz.FormatVertex += (sender, args) => {
args.VertexFormatter.Label = args.Vertex;
args.VertexFormatter.Shape = GraphvizVertexShape.Box;
args.VertexFormatter.FillColor = GraphvizColor.LightBlue;
args.VertexFormatter.Style = GraphvizVertexStyle.Filled;
};
viz.Generate(new FileDotEngine(), "output_file");
Additional Resources
- QuickGraph GitHub: https://github.com/deepakkumar1984/QuickGraph.NETStandard
- Graphviz Documentation: https://graphviz.org/documentation/
- Graph Theory: https://en.wikipedia.org/wiki/Graph_theory
- Algorithm Visualization: https://visualgo.net/en/graphds
Tips and Best Practices
Choose the Right Graph Type
- Use
AdjacencyGraphfor directed relationships - Use
UndirectedGraphfor symmetric relationships - Use
BidirectionalGraphwhen you need efficient reverse lookups
- Use
Memory Considerations
- Large graphs can consume significant memory
- Consider using value types for vertices when possible
- Reuse edge instances when appropriate
Performance
- Check graph properties before running expensive algorithms
- Cache frequently accessed results
- Use appropriate algorithms for your use case
Visualization
- Keep graphs under 100 nodes for readable visualizations
- Use colors and shapes to convey meaning
- Consider hierarchical layouts for trees
Error Handling
- Always check for cycles before topological sort
- Verify graph connectivity when required
- Handle cases where paths don't exist
Contributing
Feel free to add more examples or improve existing ones! Common additions might include:
- A* pathfinding
- Bellman-Ford algorithm
- Graph coloring
- Matching algorithms
- Planar graph testing
License
These examples are part of the QuickGraph.NETStandard project.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.1 is compatible. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.1
- System.Drawing.Common (>= 10.0.1)
- System.Drawing.Primitives (>= 4.3.0)
- System.Reflection.Emit.Lightweight (>= 4.7.0)
NuGet packages (5)
Showing the top 5 NuGet packages that depend on QuickGraph.NETStandard:
| Package | Downloads |
|---|---|
|
GraphSharp_Unofficial_NineTailLabs
Graph layout framework and control. This fork is based on https://graphsharp.codeplex.com/. This is not an official release. |
|
|
AgentFire.Lifetime.Modules
Provides a way for an app to use module-based (Start/Stop) singleton instances. |
|
|
HorizonReports.Api
Horizon Reports Api for use from plugin projects. |
|
|
Taipan
Concurrency issues detection library |
|
|
HorizonReports.Core
Horizon Reports Core Support Libraries |
GitHub repositories (1)
Showing the top 1 popular GitHub repositories that depend on QuickGraph.NETStandard:
| Repository | Stars |
|---|---|
|
tylercamp/palcalc
Comprehensive breeding solver for Palworld
|
- Added interactive menu and real-world, algorithm, and visualization demos
- Major documentation rewrite: README, quick start, architecture, contributing, changelog, marketing
- Updated solution and csproj for .NET Standard 2.1 and VS 2022+