### Basic DFS Computation in C# Source: https://github.com/kernelith/quikgraph/wiki/Depth-First-Search-Example Demonstrates the fundamental steps to initialize and run a DepthFirstSearchAlgorithm on a graph. It assumes a graph object adhering to IVertexListGraph has been created. ```csharp var graph = new AdjacencyGraph(); ... // Create algorithm var dfs = new DepthFirstSearchAlgorithm(graph); // Do the searchdfs.Compute(); ``` -------------------------------- ### Initialize Dijkstra Algorithm Source: https://github.com/kernelith/quikgraph/wiki/Dijkstra-Shortest-Distance-Example This C# code initializes the DijkstraShortestPathAlgorithm directly, which is useful for advanced usages beyond the convenience extension methods. It requires the graph and an edge cost function. The example uses a constant edge cost of 1 for simplicity. ```csharp Func, double> edgeCost = edge => 1; // Constant cost // We want to use Dijkstra on this graph var dijkstra = new DijkstraShortestPathAlgorithm>(graph, edgeCost); ``` -------------------------------- ### Recording Vertex Predecessors with DFS in C# Source: https://github.com/kernelith/quikgraph/wiki/Depth-First-Search-Example Shows how to use the TreeEdge event to record the predecessor of each vertex during a DFS traversal. This is achieved by attaching a VertexPredecessorRecorderObserver to the DFS algorithm. ```csharp Dictionary verticesPredecessors; void TreeEdgeHandler(object sender, TEdge edge) { VerticesPredecessors[edge.Target] = edge; } dfs.TreeEdge += new EdgeEventArgs(TreeEdgeHandler); ``` ```csharp var dfs = new DepthFirstSearchAlgorithm(graph); var observer = new VertexPredecessorRecorderObserver(); using (observer.Attach(dfs)) // Attach/detach to DFS events { dfs.Compute(); } // observer.VerticesPredecessors is a IDictionary that links vertices to their parent edges ``` -------------------------------- ### Topological Sort of DataSet Tables in C# Source: https://github.com/kernelith/quikgraph/wiki/Home This C# example demonstrates how to build a graph from a DataSet, compute the topological sort of its tables based on schema constraints, and print the table names in the order they should be populated or deleted in a database. It utilizes the DataSetGraph wrapper and the TopologicalSort method. ```csharp var dataSet = new DataSet(); // Get your data set DataSetGraph graph = dataSet.ToGraph(); // Wraps the dataset into a DataSetGraph foreach(DataTable table in graph.TopologicalSort()) // Applies a topological sort to the data set graph { Console.WriteLine(table.TableName); // In which order should we delete the tables? } ``` -------------------------------- ### Create Edge Cost Delegate from Dictionary Source: https://github.com/kernelith/quikgraph/wiki/Dijkstra-Shortest-Distance-Example This C# example demonstrates how to create a delegate function for edge costs from a dictionary using the `AlgorithmExtensions.GetIndexer` helper method. This is necessary because the Dijkstra algorithm expects a delegate, and directly using a dictionary requires this conversion. ```csharp Dictionary edgeCostDictionary = ...; Func edgeCost = AlgorithmExtensions.GetIndexer(edgeCostDictionary); ... ``` -------------------------------- ### C# Commenting Convention Example Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/general-coding-guidelines.md This snippet demonstrates the standard C# commenting convention, including spacing and multi-line comments. Comments should be written in proper English sentences and provide context to the code. ```csharp // This is a example comment. It showcases // the way comment must be written. ``` -------------------------------- ### C# Code with Commenting for Calculation Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/general-coding-guidelines.md An example illustrating the use of comments to explain code segments, specifically for a calculation. Comments should generally have a blank line before and after the code they describe. ```csharp int[] scores = GetScores(); // Calculate the average int count = scores.Count; double sum = scores.Sum(); double average = sum / count; Console.WriteLine(x.Average); ``` -------------------------------- ### Compute Shortest Path using Dijkstra Algorithm Instance Source: https://github.com/kernelith/quikgraph/wiki/Shortest-Path This C# code shows a full example of computing shortest paths using the DijkstraShortestPathAlgorithm class directly. It involves creating the algorithm instance, attaching an observer (VertexPredecessorRecorderObserver) to record paths, computing the paths from a source vertex, and then retrieving the path to a target vertex. ```csharp // Creating the algorithm instance var dijkstra = new DijkstraShortestPathAlgorithm>(cities, cityDistances); // Creating the observer var vis = new VertexPredecessorRecorderObserver>(); // Compute and record shortest paths using (vis.Attach(dijkstra)) { dijkstra.Compute(sourceCity); } // vis can create all the shortest path in the graph if (vis.TryGetPath(targetCity, out IEnumerable> path)) { foreach(Edge edge in path) { Console.WriteLine(edge); } } ``` -------------------------------- ### Build Shortest Path Tree with Predecessor Recorder Source: https://github.com/kernelith/quikgraph/wiki/Dijkstra-Shortest-Distance-Example This C# snippet shows how to use a VertexPredecessorRecorderObserver with the Dijkstra algorithm to build a predecessor tree. By attaching the observer and running the algorithm, the observer collects predecessor information, which can then be used to reconstruct shortest paths from the source vertex. ```csharp // Attach a Vertex Predecessor Recorder Observer to give us the paths var predecessors = new VertexPredecessorRecorderObserver>(); using (predecessors.Attach(dijkstra)) { // Run the algorithm with A set to be the source dijkstra.Compute("A"); } ``` -------------------------------- ### LINQ Filtering, Ordering, and Selection Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Example of using LINQ to filter books by a specific author, then order them by publication year, and finally select the desired information. The 'Where' clause is placed first to optimize subsequent operations on a smaller dataset. ```csharp var tolkienBooks = books.Where(x => x.Author == "Tolkien") .OrderBy(x => x.PublicationYear) .Select(x); ``` -------------------------------- ### C# Naming: Extension Methods and Classes Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Provides examples of naming conventions for extension classes and methods in C#. Extension classes are named after the type being extended, and the 'I' prefix is removed for interface extensions. ```csharp // SomeClassExtensions.cs public static class SomeClassExtensions { public static int ToInt(this SomeClass input) { // ... } } // Or public interface ISomething { } public static class SomethingExtensions { } ``` -------------------------------- ### Calculate Distances from Source using Predecessors Source: https://github.com/kernelith/quikgraph/wiki/Dijkstra-Shortest-Distance-Example This C# code iterates through the vertices of a graph and calculates the shortest distance from a source vertex ('A' in this example) using the predecessor information gathered by the VertexPredecessorRecorderObserver. It backtracks from each vertex to the source using the recorded predecessors and sums the edge costs. ```csharp foreach (string vertex in graph.Vertices) { double distance = 0; TVertex v = vertex; while (predecessors.VertexPredecessors.TryGetValue(v, out TEdge predecessor)) { distance += edgeCost(predecessor); v = predecessor.Source; } Console.WriteLine($"A -> {v}: {distance}"); } ``` -------------------------------- ### C# Fail-Fast/Exit-Fast Method Implementation Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Demonstrates the 'fail fast' and 'exit fast' principle in C# by checking for a null argument at the beginning of a method and throwing an ArgumentNullException immediately. This avoids deep nesting and improves readability compared to the 'Bad' example. ```csharp // Ok public void SomeMethod(ISomething something) { // Check for known failure condition and exit quickly if (something is null) throw new ArgumentNullException(nameof(something)); var things = _somethingElse.GetThoseThings(); // ... } // Bad public void SomeMethod(ISomething something) { if (something != null) { var things = _somethingElse.GetThoseThings(); // Lots of logic here that a maintainer has to scroll through. } else { // This should be moved to the top of the method throw new ArgumentNullException(nameof(something)); } } ``` -------------------------------- ### Compute Shortest Paths using Dijkstra Extension Method Source: https://github.com/kernelith/quikgraph/wiki/Dijkstra-Shortest-Distance-Example This C# snippet demonstrates how to compute shortest paths from a root vertex to all other vertices in a graph using the Dijkstra extension method provided by QuikGraph. It assumes a graph and a root vertex are already defined, and it uses a simple edge cost function. The result is a function that can be queried for the path to a specific target vertex. ```csharp using QuikGraph; using QuikGraph.Algorithms; IVertexAndEdgeListGraph graph = ...; Func edgeCost = edge => 1; // Constant cost TVertex root = ...; // Compute shortest paths TryFunc> tryGetPaths = graph.ShortestPathsDijkstra(edgeCost, root); // Query path for given vertices TVertex target = ...; if (tryGetPaths(target, out IEnumerable path)) { foreach(TEdge edge in path) { Console.WriteLine(edge); } } ``` -------------------------------- ### BidirectionalGraph C# Example: Iterating In-Edges Source: https://github.com/kernelith/quikgraph/wiki/BidirectionalGraph This C# code snippet demonstrates how to create and populate a BidirectionalGraph and then iterate through the in-edges of each vertex. It utilizes the BidirectionalGraph class from the QuikGraph library. ```csharp var graph = new BidirectionalGraph>(); ... foreach(int vertex in graph.Vertices) { foreach(Edge edge in graph.InEdges(vertex)) { Console.WriteLine(edge); } } ``` -------------------------------- ### C# Filtered Depth First Search with outEdgesFilter Source: https://github.com/kernelith/quikgraph/wiki/Depth-First-Search-Example This C# code snippet demonstrates how to perform a filtered Depth First Search (DFS) using QuikGraph. It defines a graph, a filtering function 'Filter' that processes outgoing edges, and then initializes the 'DepthFirstSearchAlgorithm' with this filter. The 'outEdgesFilter' parameter in the DFS algorithm allows for selective traversal by controlling which edges are considered from a visited vertex. Dependencies include the QuikGraph library. ```csharp var graph = new AdjacencyGraph>(); // Setup your graph the way you want IEnumerable> Filter(IEnumerable> edges) { // Your filtering algorithm here // Ex: edges.Where(e => ...) // Or // if (...) // { // yield ...; // } } // Create algorithm var dfs = new DepthFirstSearchAlgorithm>( null, graph, new Dictionary(), Filter); // <= // Do the search dfs.Compute(); ``` -------------------------------- ### C#: Create and Manage Graphs with QuikGraph Source: https://context7.com/kernelith/quikgraph/llms.txt Demonstrates how to create directed and undirected graphs, add vertices and edges, and perform basic graph queries using QuikGraph. This includes creating graphs from edge collections, adding elements individually or in bulk, and checking for the existence of vertices and edges. ```csharp using QuikGraph; using QuikGraph.Algorithms; // Create a directed graph from edge collection var edges = new[] { new Edge(1, 2), new Edge(0, 1), new Edge(2, 3) }; var graph = edges.ToAdjacencyGraph>(); // Create an empty graph and add elements var customGraph = new AdjacencyGraph>(); customGraph.AddVertex(1); customGraph.AddVertex(2); customGraph.AddEdge(new TaggedEdge(1, 2, "route-A")); // Bulk operations customGraph.AddVertexRange(new[] { 3, 4, 5 }); customGraph.AddEdgeRange(new[] { new TaggedEdge(2, 3, "route-B"), new TaggedEdge(3, 4, "route-C") }); // Add edge with implicit vertex addition var edge = new TaggedEdge(10, 11, "new-connection"); customGraph.AddVerticesAndEdge(edge); // Query graph properties Console.WriteLine($"Vertices: {graph.VertexCount}, Edges: {graph.EdgeCount}"); bool hasVertex = graph.ContainsVertex(2); bool hasEdge = graph.ContainsEdge(edges[0]); ``` -------------------------------- ### C# BidirectionalGraphAdapter Usage Example Source: https://github.com/kernelith/quikgraph/wiki/BidirectionalGraphAdapter This C# code demonstrates how to instantiate and use the BidirectionalGraphAdapter with an AdjacencyGraph. It shows how to iterate through vertices and access incoming edges. ```csharp var graph = new AdjacencyGraph>(); var adapterGraph = new BidirectionalGraphAdapter>(graph); ... foreach(int vertex in adapterGraph.Vertices) { foreach(Edge edge in graph.InEdges(vertex)) { Console.WriteLine(edge); } } ``` -------------------------------- ### Instantiate Adjacency Graph (C#) Source: https://github.com/kernelith/quikgraph/wiki/Creating-Graphs Demonstrates how to create a new instance of an AdjacencyGraph with specific vertex and edge types. This method allows for direct control over the graph's structure, specifying integer vertices and string-tagged edges. ```csharp var graph = new AdjacencyGraph>(); ``` -------------------------------- ### Wrap Dictionary into Graph (C#) Source: https://github.com/kernelith/quikgraph/wiki/Creating-Graphs Shows how to wrap an existing dictionary representing graph connections into a QuikGraph instance without reallocating memory. It supports both using the extension method and calling the static method directly. ```csharp Dictionary dictionary = ...; // Vertex -> Target edges var graph = dictionary.ToDelegateVertexAndEdgeListGraph( kv => Array.ConvertAll(kv.Value, v => new Edge(kv.Key, v))); // Without extension method var graph = GraphExtensions.ToDelegateVertexAndEdgeListGraph( dictionary, kv => Array.ConvertAll(kv.Value, v => new Edge(kv.Key, v))); ``` -------------------------------- ### C#: Dijkstra's Shortest Path Algorithm with QuikGraph Source: https://context7.com/kernelith/quikgraph/llms.txt Shows how to use Dijkstra's algorithm in QuikGraph to find the shortest paths between vertices in a weighted graph. It covers both a simple approach using extension methods and a more advanced method involving observer patterns for predecessor tracking. ```csharp using QuikGraph; using QuikGraph.Algorithms; using QuikGraph.Algorithms.ShortestPath; using QuikGraph.Algorithms.Observers; // Create graph with weighted edges var graph = new AdjacencyGraph>(); graph.AddVerticesAndEdgeRange(new[] { new Edge("A", "B"), new Edge("A", "C"), new Edge("B", "D"), new Edge("C", "D"), new Edge("D", "E") }); // Define edge costs var edgeCosts = new Dictionary, double> { [new Edge("A", "B")] = 1.0, [new Edge("A", "C")] = 4.0, [new Edge("B", "D")] = 2.0, [new Edge("C", "D")] = 1.0, [new Edge("D", "E")] = 3.0 }; Func, double> edgeCost = AlgorithmExtensions.GetIndexer(edgeCosts); // Simple approach using extension method TryFunc>> tryGetPaths = graph.ShortestPathsDijkstra(edgeCost, "A"); if (tryGetPaths("E", out IEnumerable> path)) { Console.WriteLine("Path from A to E:"); foreach (var edge in path) Console.WriteLine($" {edge.Source} -> {edge.Target}"); } // Advanced approach with predecessor tracking var dijkstra = new DijkstraShortestPathAlgorithm>(graph, edgeCost); var predecessorRecorder = new VertexPredecessorRecorderObserver>(); using (predecessorRecorder.Attach(dijkstra)) { dijkstra.Compute("A"); } // Calculate distances to all vertices foreach (string vertex in graph.Vertices) { double distance = 0; string v = vertex; while (predecessorRecorder.VertexPredecessors.TryGetValue(v, out Edge predecessor)) { distance += edgeCost(predecessor); v = predecessor.Source; } Console.WriteLine($"A -> {vertex}: {distance}"); } ``` -------------------------------- ### Facade Pattern for Static Classes in C# Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/guidelines/csharp-best-practices.md Demonstrates how to create a facade pattern using interfaces and wrapper classes to manage dependencies on static .NET Framework classes. This approach improves testability and control over non-idempotent or infrastructure-dependent static members. ```csharp public interface IFile { bool Exists(string path); } public class FileWrapper : IFile { public bool Exists(string path) { return File.Exists(path); } } ``` -------------------------------- ### Explicit vs. Implicit Scope in C# Classes Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Contrasts the use of explicit scope modifiers (public, private) with implicit scoping in C# class definitions. The 'Ok' example demonstrates preferred explicit scoping for members and methods, enhancing code clarity and maintainability. ```csharp // Ok public class Something { private const int MaximumAge = 100; public int Age { get; set; } public void SayHello() { Console.WriteLine("Hello"); } } // Bad class Something { const int MaximumAge = 100; int Age { get; set; } void SayHello() { Console.WriteLine("Hello"); } } ``` -------------------------------- ### Array Initialization Syntax in C# Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Presents different ways to initialize arrays in C#. It shows the concise syntax for initializing arrays on the declaration line, using `var` with explicit instantiation, and initializing elements individually when an array size is specified. ```csharp string[] vowels1 = { "a", "e", "i", "o", "u" }; // If you use explicit instantiation, you can use var. var vowels2 = new string[] { "a", "e", "i", "o", "u" }; // If you specify an array size, you must initialize the elements one at a time. var vowels3 = new string[5]; vowels3[0] = "a"; vowels3[1] = "e"; // Etc ``` -------------------------------- ### Incremental Connected Components Algorithm in C# Source: https://github.com/kernelith/quikgraph/wiki/Incremental-Connected-Components Demonstrates how to use the IncrementalConnectedComponents algorithm from QuikGraph. It initializes a graph, adds vertices, and then uses a delegate to track the number of connected components as edges are added. The delegate returns the current component count and a dictionary mapping vertices to their component IDs. ```csharp var graph = new AdjacencyGraph>(); graph.AddVertexRange(new int[] { 0, 1, 2, 3 }); graph.IncrementalConnectedComponents(out Func>> getComponents); KeyValuePair> current = getComponents(); Assert.AreEqual(4, current.Key); graph.AddEdge(new Edge(0, 1)); current = getComponents(); // Query algorithm again Assert.AreEqual(3, current.Key); ``` -------------------------------- ### Generic Type Naming Conventions in C# Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/guidelines/csharp-best-practices.md Illustrates recommended naming conventions for generic types in C#. For single generic types, `T` is preferred unless a more specific name is suitable. For multiple generic types, use `T` followed by a descriptive name, ensuring the type starts with a capital letter. ```csharp public interface ISomething ``` ```csharp public interface IService ``` -------------------------------- ### Object Initializers for Simplified Object Creation in C# Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Demonstrates the use of object initializers in C# to simplify the creation and population of collections like `List` and `Dictionary`. This syntax reduces boilerplate code, making object instantiation more concise. ```csharp // Ok var myObjects = new List { new SomeObject("value1"), new SomeObject("value2"), }; var studentById = new Dictionary { [123456] = new Student { Name = "John Doe", Age = 17} }, [456789] = new Student { Name = "Dany Doe", Age = 16} }, }; ``` -------------------------------- ### Condensate Graph Weakly Connected and Strongly Connected Source: https://github.com/kernelith/quikgraph/wiki/Condensation-Graph Demonstrates how to use the AlgorithmExtensions class to perform weakly and strongly connected condensations on a graph. This involves calling specific extension methods on an input graph object. No specific dependencies are mentioned beyond the graph structure itself. ```csharp IVertexAndEdgeListGraph graph = ...; // Input graph // Condensations var weaklyCondensed = graph.CondensateWeaklyConnected(); var stronglyCondensed = graph.CondensateStronglyConnected(); ``` -------------------------------- ### LINQ Method Syntax for Filtering and Projection Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Demonstrates using LINQ's method syntax to filter a collection of books by author and select their names. This approach is preferred over query syntax for its conciseness. It takes a collection of books as input and outputs a collection of book names. ```csharp var tolkienBooks = books.Where(x => x.Author == "Tolkien") .Select(x => x.Name); ``` -------------------------------- ### Add Edge and Vertices Implicitly (C#) Source: https://github.com/kernelith/quikgraph/wiki/Creating-Graphs Shows how to add an edge to the graph, which will also implicitly add the source and target vertices if they do not already exist. This simplifies graph construction when vertex existence is not pre-guaranteed. ```csharp // vertex3, vertex4 are not added into the graph yet var edge2 = new TaggedEdge(vertex3, vertex4, "hello"); graph.AddVerticesAndEdge(edge2); ``` -------------------------------- ### Bidirectional Graph Operations in C# Source: https://context7.com/kernelith/quikgraph/llms.txt Demonstrates how to create and operate on bidirectional graphs using QuikGraph. It covers adding vertices and edges, iterating through in-edges and out-edges, querying degrees, checking for edges, and performing removal operations. ```csharp using QuikGraph; // Create bidirectional graph var graph = new BidirectionalGraph>(); // Add vertices and edges graph.AddVerticesAndEdgeRange(new[] { new Edge(1, 2), new Edge(2, 3), new Edge(3, 4), new Edge(1, 3), new Edge(2, 4) }); // Iterate through out-edges (edges leaving a vertex) Console.WriteLine("Out-edges of vertex 2:"); foreach (var edge in graph.OutEdges(2)) { Console.WriteLine($" {edge.Source} -> {edge.Target}"); } // Iterate through in-edges (edges entering a vertex) Console.WriteLine("In-edges of vertex 3:"); foreach (var edge in graph.InEdges(3)) { Console.WriteLine($" {edge.Source} -> {edge.Target}"); } // Query edge degrees int outDegree = graph.OutDegree(2); int inDegree = graph.InDegree(3); Console.WriteLine($"Vertex 2 out-degree: {outDegree}"); Console.WriteLine($"Vertex 3 in-degree: {inDegree}"); // Check for specific edges bool hasOutEdge = graph.TryGetOutEdges(1, out IEnumerable> outEdges); bool hasInEdge = graph.TryGetInEdges(4, out IEnumerable> inEdges); // Remove operations maintain both edge directions var edgeToRemove = new Edge(2, 3); graph.RemoveEdge(edgeToRemove); graph.RemoveVertex(4); // Removes all connected in-edges and out-edges ``` -------------------------------- ### Compute and Display Strongly Connected Components in C# Source: https://github.com/kernelith/quikgraph/wiki/Strongly-Connected-Components This snippet demonstrates how to compute and display the strongly connected components of a directed graph using the QuikGraph library in C#. It initializes a graph, computes the components, and then iterates through the results to print component information. The `StronglyConnectedComponents` extension method is used, which returns the number of components and populates a dictionary mapping vertices to their component IDs. ```csharp IVertexListGraph graph = ...; IDictionary components = new Dictionary(); int componentCount = graph.StronglyConnectedComponents(components); if (componentCount != 0) { Console.WriteLine("Warning the graph is not strongly connected"); foreach (KeyValuePair kv in components) { Console.WriteLine($"{kv.Value}-{kv.Key}"); } } ``` -------------------------------- ### Initialize and Iterate BidirectionalMatrixGraph Source: https://github.com/kernelith/quikgraph/wiki/BidirectionalMatrixGraph Demonstrates the initialization of a BidirectionalMatrixGraph with a known vertex count and how to iterate through its vertices to access incoming edges. This is useful for inspecting graph connectivity in dense graph scenarios. ```csharp int vertexCount = ...; // Must be known a-priori var graph = new BidirectionalMatrixGraph>(vertexCount); foreach(int vertex in graph.Vertices) { foreach(Edge edge in graph.InEdges(vertex)) { Console.WriteLine(edge); } } ``` -------------------------------- ### C# Allman Style Braces and Single Return/Throw Exceptions Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Demonstrates the correct use of Allman style braces (opening brace on a new line) in C#. It also shows acceptable exceptions for single 'return' or 'throw' statements, and highlights incorrect formatting. ```csharp // Ok if (a == b) { c = d; } // Acceptable if (a == b) return; // Bad if (a == b) { c = d; } // Bad - inconsistent style if (a == b) c = d; else { c = e; } ``` -------------------------------- ### Maximum Bipartite Matching Algorithm in C# Source: https://context7.com/kernelith/quikgraph/llms.txt This C# snippet demonstrates how to compute the maximum cardinality matching in a bipartite graph. It transforms the problem into a maximum flow problem and utilizes the QuikGraph library's `MaximumBipartiteMatchingAlgorithm`. The input is a graph with defined worker and task vertices, and edges representing capabilities. The output is a list of matched pairs and counts of total matches and unmatched workers. ```csharp using QuikGraph; using QuikGraph.Algorithms; // Create bipartite graph (workers to tasks) var graph = new AdjacencyGraph>(); var workers = new[] { "Worker1", "Worker2", "Worker3" }; var tasks = new[] { "TaskA", "TaskB", "TaskC", "TaskD" }; // Add all vertices graph.AddVertexRange(workers); graph.AddVertexRange(tasks); // Add edges (worker capabilities) graph.AddEdgeRange(new[] { new Edge("Worker1", "TaskA"), new Edge("Worker1", "TaskB"), new Edge("Worker2", "TaskB"), new Edge("Worker2", "TaskC"), new Edge("Worker3", "TaskC"), new Edge("Worker3", "TaskD") }); // Define vertex and edge factories VertexFactory vertexFactory = () => Guid.NewGuid().ToString(); EdgeFactory> edgeFactory = (source, target) => new Edge(source, target); // Compute maximum bipartite matching var matching = new MaximumBipartiteMatchingAlgorithm>( graph, workers, tasks, vertexFactory, edgeFactory); matching.Compute(); // Display matched pairs Console.WriteLine("Maximum matching:"); foreach (var edge in matching.MatchedEdges) { Console.WriteLine($" {edge.Source} assigned to {edge.Target}"); } Console.WriteLine($"\nTotal matches: {matching.MatchedEdges.Count()}"); Console.WriteLine($"Unmatched workers: {workers.Length - matching.MatchedEdges.Count()}"); ``` -------------------------------- ### Create Graph from C# Dictionary (Edge List) and Run Dijkstra Source: https://context7.com/kernelith/quikgraph/llms.txt This snippet shows how to create a QuikGraph graph from a C# Dictionary representing a list of edges, where keys are source vertices and values are lists of target vertices. It then utilizes the graph with Dijkstra's algorithm to find the shortest path between two vertices. The input is a Dictionary of string lists, and the output is the shortest path as a collection of edges. ```csharp using QuikGraph; using System.Linq; // Alternative: Dictionary of edge lists var edgeDict = new Dictionary> { ["A"] = new List { "B", "C" }, ["B"] = new List { "D" }, ["C"] = new List { "D", "E" }, ["D"] = new List { "E" }, ["E"] = new List() }; var stringGraph = edgeDict.ToDelegateVertexAndEdgeListGraph( kv => kv.Value.Select(target => new Edge(kv.Key, target))); // Use graph with algorithms var paths = stringGraph.ShortestPathsDijkstra(e => 1.0, "A"); if (paths("E", out var shortestPath)) { Console.WriteLine("Shortest path A -> E:"); foreach (var edge in shortestPath) { Console.WriteLine($" {edge.Source} -> {edge.Target}"); } } ``` -------------------------------- ### Create Graph from C# Dictionary (Adjacency List) Source: https://context7.com/kernelith/quikgraph/llms.txt This snippet demonstrates creating a QuikGraph graph from an existing C# Dictionary representing an adjacency list. It uses a zero-copy conversion method, avoiding unnecessary memory allocations. The input is a Dictionary where keys are vertices and values are arrays of adjacent vertices. The output is a QuikGraph instance that can be queried for vertex and edge counts, and iterated to display outgoing edges. ```csharp using QuikGraph; using System.Linq; // Existing adjacency list representation var adjacencyDict = new Dictionary { [1] = new[] { 2, 3 }, [2] = new[] { 3, 4 }, [3] = new[] { 4 }, [4] = new[] { 5 }, [5] = new int[] { } }; // Wrap dictionary as graph (zero-copy conversion) var graph = adjacencyDict.ToDelegateVertexAndEdgeListGraph( kv => Array.ConvertAll(kv.Value, target => new Edge(kv.Key, target))); // Query the wrapped graph Console.WriteLine($"Vertices: {graph.VertexCount}"); Console.WriteLine($"Edges: {graph.EdgeCount}"); foreach (var vertex in graph.Vertices) { var outEdges = graph.OutEdges(vertex); Console.WriteLine($"Vertex {vertex} has {outEdges.Count()} out-edges"); foreach (var edge in outEdges) { Console.WriteLine($" {edge.Source} -> {edge.Target}"); } } ``` -------------------------------- ### Generate DOT graph file using GraphvizAlgorithm Source: https://github.com/kernelith/quikgraph/wiki/Visualization-Using-Graphviz Renders an IEdgeListGraph to a DOT file using the GraphvizAlgorithm class and a FileDotEngine. This method saves the generated DOT string to a specified file. Customization of graph elements is possible through properties and events. ```csharp IEdgeListGraph graph = ...; var graphviz = new GraphvizAlgorithm(graph); // Or string outputFilePath = graphviz.Generate(new FileDotEngine(), "dotOutputGraph"); ``` -------------------------------- ### Add Vertices to Graph (C#) Source: https://github.com/kernelith/quikgraph/wiki/Creating-Graphs Illustrates the process of adding individual vertices to an existing graph instance. This is a fundamental operation for populating the graph with nodes before adding connections. ```csharp int vertex1 = 1; int vertex2 = 2; graph.AddVertex(vertex1); graph.AddVertex(vertex2); ``` -------------------------------- ### C# Naming: Pascal Case for Types, Methods, Constants Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Demonstrates the use of Pascal casing for class names, constant fields, and method names in C#. This convention improves code readability and consistency. ```csharp public class SomeClass { private const int DefaultSize = 100; public void SomeMethod() { } } ``` -------------------------------- ### C# Empty Constructor Formatting Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Shows the standard C# formatting for constructors that have no body, ensuring consistency even for simple cases. ```csharp public SomeClass() { } public SomeClass(string parameter) : base(parameter) { } ``` -------------------------------- ### Compute Shortest Path using Dijkstra Extension Method Source: https://github.com/kernelith/quikgraph/wiki/Shortest-Path This C# code snippet demonstrates how to compute the shortest path in a graph using the Dijkstra algorithm via an extension method from AlgorithmExtensions. It takes a graph, an edge weight delegate, and source/target vertices as input. It returns a delegate to retrieve the path, handling cases where no path exists. ```csharp IVertexAndEdgeListGraph> cities = ...; // A graph of cities Func, double> cityDistances = ...; // A delegate that gives the distance between cities int sourceCity = 0; // Starting city int targetCity = 0; // Ending city // Returns a delegate that can be used to retrieve the paths TryFunc> tryGetPath = cities.ShortestPathsDijkstra(cityDistances, sourceCity); // Enumerating path to targetCity, if any if (tryGetPath(targetCity, out IEnumerable> path)) { foreach (Edge edge in path) { Console.WriteLine(edge); } } ``` -------------------------------- ### Add Vertex and Edge Ranges (C#) Source: https://github.com/kernelith/quikgraph/wiki/Creating-Graphs Explains how to add multiple vertices or edges to the graph in a single operation using range methods. This includes adding edges that also implicitly add their vertices. ```csharp // Vertex range graph.AddVertexRange(new[] { vertex5, vertex6 }); // Edge range graph.AddEdgeRange(new[] { edge3, edge4 }); // Edge range (and implicitly vertices) graph.AddVerticesAndEdgeRange(new[] { edge5, edge6 }); ``` -------------------------------- ### Visualize DataSetGraph with Graphviz Source: https://github.com/kernelith/quikgraph/wiki/DataSetGraph Illustrates how to generate a Graphviz DOT language string representation of a DataSetGraph using the ToGraphviz extension method. This enables visualization of the graph structure. ```csharp DataSet dataSet = new (); DataSetGraph graph = dataSet.ToGraph(); string dot = graph.ToGraphviz(); ``` -------------------------------- ### Depth First Search with Event Handling in C# Source: https://context7.com/kernelith/quikgraph/llms.txt Performs depth-first traversal on a graph using QuikGraph, with support for event handling to track vertex discovery, tree edges, back edges, and finished vertices. It also demonstrates predecessor tracking and filtered DFS. ```csharp using QuikGraph; using QuikGraph.Algorithms.Search; using QuikGraph.Algorithms.Observers; var graph = new AdjacencyGraph>(); graph.AddVerticesAndEdgeRange(new[] { new Edge("u", "v"), new Edge("u", "x"), new Edge("v", "y"), new Edge("y", "x"), new Edge("x", "v"), new Edge("w", "z"), new Edge("w", "y") }); // Basic DFS var dfs = new DepthFirstSearchAlgorithm>(graph); dfs.Compute(); // DFS with predecessor tracking var predecessorObserver = new VertexPredecessorRecorderObserver>(); using (predecessorObserver.Attach(dfs)) { dfs.Compute("u"); } // Access the predecessor tree var predecessors = predecessorObserver.VertexPredecessors; foreach (var kvp in predecessors) { Console.WriteLine($"{kvp.Value.Source} -> {kvp.Key}"); } // DFS with custom event handlers dfs.DiscoverVertex += vertex => Console.WriteLine($"Discovered: {vertex}"); dfs.TreeEdge += edge => Console.WriteLine($"Tree edge: {edge}"); dfs.BackEdge += edge => Console.WriteLine($"Back edge: {edge}"); dfs.FinishVertex += vertex => Console.WriteLine($"Finished: {vertex}"); // Process all connected components dfs.ProcessAllComponents = true; dfs.Compute(); // Filtered DFS to avoid certain graph regions IEnumerable> Filter(IEnumerable> edges) { return edges.Where(e => e.Target != "x"); // Skip edges leading to "x" } var filteredDfs = new DepthFirstSearchAlgorithm>( null, graph, new Dictionary(), Filter); filteredDfs.Compute(); ``` -------------------------------- ### AdjacencyGraph Initialization and Traversal in C# Source: https://github.com/kernelith/quikgraph/wiki/AdjacencyGraph Demonstrates how to initialize an AdjacencyGraph> and iterate through its vertices and their corresponding out-edges. This requires the QuikGraph library. ```csharp var graph = new AdjacencyGraph>(); ... foreach(int vertex in graph.Vertices) { foreach(Edge edge in graph.OutEdges(vertex)) { Console.WriteLine(edge); } } ``` -------------------------------- ### Ranked Shortest Path Algorithm - C# Source: https://github.com/kernelith/quikgraph/wiki/Ranked-Shortest-Path Demonstrates how to find the k-th shortest paths in a directed weighted graph using the Hoffman-Pavlet algorithm in C#. It requires a graph object, an edge weight function, source and target vertices, and the maximum number of paths to find. The function returns an enumerable collection of paths, where each path is a sequence of edges. ```csharp IBidirectionalGraph graph = ...; Func edgeWeights = ...; TVertex source = ...; TVertex target = ...; int maxPathCount = 5; foreach(IEnumerable path in graph.RankedShortestPathHoffman(edgeWeights, source, target, maxPathCount)) { ... } ``` -------------------------------- ### Undirected Graph Operations in C# Source: https://context7.com/kernelith/quikgraph/llms.txt Illustrates the creation and manipulation of undirected graphs using QuikGraph. This includes adding vertices and edges, iterating through adjacent edges and vertices, querying degrees, and checking for edge existence. ```csharp using QuikGraph; // Create undirected graph var graph = new UndirectedGraph>(); // Add vertices and edges graph.AddVertexRange(new[] { 1, 2, 3, 4, 5 }); graph.AddEdgeRange(new[] { new Edge(1, 2), new Edge(2, 3), new Edge(3, 4), new Edge(4, 5), new Edge(1, 5) }); // Iterate through adjacent edges (all edges connected to a vertex) Console.WriteLine("Adjacent edges of vertex 2:"); foreach (var edge in graph.AdjacentEdges(2)) { Console.WriteLine($" {edge.Source} <-> {edge.Target}"); } // Query adjacent vertices var adjacentVertices = graph.AdjacentEdges(3) .Select(e => e.Source == 3 ? e.Target : e.Source); Console.WriteLine($"Neighbors of vertex 3: {string.Join(", ", adjacentVertices)}"); // Check connectivity int degree = graph.AdjacentDegree(3); Console.WriteLine($"Degree of vertex 3: {degree}"); // Check if edge exists (order doesn't matter in undirected graphs) bool hasEdge = graph.ContainsEdge(new Edge(1, 2)) || graph.ContainsEdge(new Edge(2, 1)); ``` -------------------------------- ### Minimum Spanning Tree (MST) Algorithms in C# Source: https://context7.com/kernelith/quikgraph/llms.txt Finds a subset of edges in an undirected weighted graph that connects all vertices with the minimum possible total edge weight. Implements both Prim's and Kruskal's algorithms. Requires QuikGraph library and a way to define edge weights. ```csharp using QuikGraph; using QuikGraph.Algorithms; // Create undirected weighted graph var graph = new UndirectedGraph>(); graph.AddVerticesAndEdgeRange(new[] { new Edge("A", "B"), new Edge("A", "C"), new Edge("B", "C"), new Edge("B", "D"), new Edge("C", "D"), new Edge("C", "E"), new Edge("D", "E") }); // Define edge weights var weights = new Dictionary, double> { [new Edge("A", "B")] = 4.0, [new Edge("A", "C")] = 2.0, [new Edge("B", "C")] = 1.0, [new Edge("B", "D")] = 5.0, [new Edge("C", "D")] = 8.0, [new Edge("C", "E")] = 10.0, [new Edge("D", "E")] = 2.0 }; Func, double> edgeWeights = e => weights[e]; // Prim's algorithm (good for dense graphs) IEnumerable> primMST = graph.MinimumSpanningTreePrim(edgeWeights); Console.WriteLine("Minimum Spanning Tree (Prim):"); double primTotal = 0; foreach (var edge in primMST) { double weight = edgeWeights(edge); primTotal += weight; Console.WriteLine($" {edge.Source} - {edge.Target}: {weight}"); } Console.WriteLine($"Total weight: {primTotal}"); // Kruskal's algorithm (good for sparse graphs) IEnumerable> kruskalMST = graph.MinimumSpanningTreeKruskal(edgeWeights); Console.WriteLine("\nMinimum Spanning Tree (Kruskal):"); double kruskalTotal = 0; foreach (var edge in kruskalMST) { double weight = edgeWeights(edge); kruskalTotal += weight; Console.WriteLine($" {edge.Source} - {edge.Target}: {weight}"); } Console.WriteLine($"Total weight: {kruskalTotal}"); ``` -------------------------------- ### Compute Maximum Bipartite Matching in C# Source: https://github.com/kernelith/quikgraph/wiki/Maximum-Bipartite-Matching Demonstrates how to compute the maximum bipartite matching using QuikGraph. It requires a mutable graph, two distinct vertex sets, and factories for creating vertices and edges. The algorithm transforms the graph into a maximum flow problem and returns the set of matched edges. ```csharp using QuikGraph; using QuikGraph.Algorithms.MaximumFlow; // Assuming TVertex and TEdge are defined elsewhere // We need a graph and two sets of vertices IMutableVertexAndEdgeListGraph> graph = ...; // Sets a and b must be distinct, and their union must be equal to the set of all vertices in the graph IEnumerable vertexSetA = ...; IEnumerable vertexSetB = ...; // These functions used to create new vertices and edges during the execution of the algorithm // All added objects are removed before the computation returns VertexFactory vertexFactory = ...; // Some method which creates a new TVertex EdgeFactory> edgeFactory = (source, target) => new Edge(source, target); // Computing the maximum bipartite match var maxMatch = new MaximumBipartiteMatchingAlgorithm( graph, vertexSetA, vertexSetB, vertexFactory, edgeFactory); // Use the MatchedEdges property to access the computed maximum match ProcessResult(maxMatch.MatchedEdges); ``` -------------------------------- ### Add Edge to Graph (C#) Source: https://github.com/kernelith/quikgraph/wiki/Creating-Graphs Demonstrates adding a single tagged edge to a graph where the vertices have already been added. This method requires the edge object, including its source, target, and tag, to be created beforehand. ```csharp var edge1 = new TaggedEdge(vertex1, vertex2, "hello"); graph.AddEdge(edge1); ``` -------------------------------- ### Create DataSetGraph from DataSet Source: https://github.com/kernelith/quikgraph/wiki/DataSetGraph Demonstrates how to create a DataSetGraph from a DataSet using the ToGraph extension method. This is a fundamental step for utilizing DataSetGraph functionalities. ```csharp using QuikGraph.Data; DataSet dataSet = ...; DataSetGraph graph = dataSet.ToGraph(); ``` -------------------------------- ### Convert graph to DOT string using extension method Source: https://github.com/kernelith/quikgraph/wiki/Visualization-Using-Graphviz Converts an IEdgeListGraph to a DOT string using the `ToGraphviz` extension method. This provides a more concise way to generate DOT output. Custom initialization of the GraphvizAlgorithm can be provided via a lambda expression. ```csharp IEdgeListGraph graph = ...; string dotGraph = graph.ToGraphviz(); // Or using a custom init for the algorithm string dotGraph = graph.ToGraphviz(algorithm => { // Custom init example algorithm.CommonVertexFormat.Shape = GraphvizVertexShape.Diamond; algorithm.CommonEdgeFormat.ToolTip = "Edge tooltip"; algorithm.FormatVertex += (sender, args) => { args.VertexFormat.Label = $"Vertex {args.Vertex}"; }; }); ``` -------------------------------- ### Convert QuikGraph to MSAGL Graph Source: https://github.com/kernelith/quikgraph/wiki/Visualization-Using-MSAGL Demonstrates how to convert an IEdgeListGraph from QuikGraph into an MSAGL Graph object. This allows for visualization using MSAGL's rendering capabilities. It shows both a verbose and a more concise method. ```csharp IEdgeListGraph> graph = ...; var populator = graph.CreateMsaglPopulator>(graph); populator.Compute(); Graph msaglGraph = populator.MsaglGraph; // Easy way Graph msaglGraph = graph.ToMsaglGraph(); ``` -------------------------------- ### C# Auto-Property Formatting Source: https://github.com/kernelith/quikgraph/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Illustrates the concise single-line format for C# auto-properties, contrasting it with the verbose multi-line alternative. ```csharp // Ok public int Property { get; set; } // Bad public int Property { get; set; } ``` -------------------------------- ### UndirectedGraph Initialization and Traversal (C#) Source: https://github.com/kernelith/quikgraph/wiki/UndirectedGraph Demonstrates how to initialize an UndirectedGraph and iterate through its vertices and adjacent edges. This class is mutable, serializable, and cloneable. ```csharp var graph = new UndirectedGraph>(); ... foreach(int vertex in graph.Vertices) { foreach(Edge edge in graph.AdjacentEdges(vertex)) { Console.WriteLine(edge); } } ```