The Best Article Out There to Understand Graphs in C#

Graphs are are an integral part of communication networks, maps, data models and much more. Graphs are used to represent information with appealing visuals. For example, organization hierarchy is represented using graphs. Graph transformation systems use rules to manipulate graphs in memory and much more.

This article will help us unravel the detailed technicalities of graphs in C#, their terminologies, representations, and the operations performed in graphs, such as graph traversal along with important graph applications.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Is Graph Data Structure in C#?

A graph is a non-linear data structure trumped-up of nodes and edges. Edges are lines or arcs that link any two nodes in a graph, and nodes are also called vertices. A graph can be more explicitly defined as,

A graph comprises a finite number of vertices (or nodes) and a set of Edges that connect them.

what-is-graph-data-structure-in-C#

The set of vertices V = {A,B,C,D,E} and the set of edges E ={AB, AC, BD, BE} are shown in the graph above.

In this post, we'll look at some different forms of graphs after learning what a graph data structure is.

Types of Graphs in C#

There are various sorts of graphs based on the position of these nodes and vertices, such as:

  • Undirected Graph

A directed graph is defined as an ordered pair of vertices. The Graph's edges represent a precise path from one vertex to the next. The direction is from V1 to V2 when an edge is represented as (V1, V2). The starting node, or start vertex, is the first element, V1. The terminal node, also known as the end vertex, is the second part V2.

undirected-graph-in-types-of-graph

  • Directed Graph

A directed graph (digraph) is a graph with edges that have different orientations, i.e., an edge (x, y) is not the same as an edge (x, y) (y, x).

directed-graph-in-types-of-graph

  • Cyclic Graph

An acyclic Graph is defined as one that has at least one cycle.

cyclic-graph-in-graphs

  • Acyclic Graph

An acyclic graph does not have any cycles in it.

acyclic-graph-in-graph.

  • Directed Acyclic Graph(DAG)

A DAG (Directed Acyclic Graph) is a directed graph with no cycles.

directed-acyclic-graph-in-types-of-graph.

  • Multi Graph

A multigraph is an undirected graph that allows numerous edges (and occasionally loops). Two or more edges that connect the same two vertices are multiple edges. A loop is a directed or undirected edge that connects a vertex to itself, and it may or may not be permitted.

multi-graph-types-in-graph.

  • Simple Graph

In contrast to a multigraph, a simple graph is an undirected graph in which multiple edges and loops are forbidden. Every vertex in a simple graph with n vertices has a degree of n-1.

simple-graph-in-types-of-graph.

  • Weighted Graph

Every edge in a weighted graph has a value (weight) associated with it. Instead of weight, we can use the phrases cost or length.

weighted-graph-in-types-of-graph.

  • Unweighted Graph

Every edge in an unweighted graph does not have a value (weight) associated with it. To put it another way, an unweighted graph is a weighted graph with all edge weights equal to one. By default, all graphs are presumed to be unweighted unless otherwise stated.

unweighted-graph-in-types-of-graph

  • Complete Graph

Every two vertices in a complete graph are adjacent, and all edges that could exist are present.

complete-graph-in-types-of-graph

  • Connected Graph

Every pair of vertices has a path linking them in a connected graph. To put it another way, there are no inaccessible vertices. A graph that is not connected is referred to as a disconnected graph.

connected-graph-in-types-of-graph

  • Disconnected 

If at least two of the Graph's vertices are not connected by a path, the Graph is disconnected. When a graph G is disconnected, every maximally connected subgraph of G is referred to as a connected component of G.

disconnected-graph-in-types-of-graph.

Following our graphs discussion in C#, we'll look at certain graph terminologies.

Learn From The Best Mentors in the Industry!

Automation Testing Masters ProgramExplore Program
Learn From The Best Mentors in the Industry!

Graph Terminologies

The terms we utilized in the graph data structure are listed below.

  • Edges are two basic pieces from which graphs are built (together with vertices). Each edge has two ends, called vertices, to which it is connected.
  • If two vertices are endpoints of the same edge, they are neighboring.
  • A vertex's outgoing edges are directed edges in which the vertex is the origin.
  • A vertex's incoming edges are directed edges with the vertex as the destination.
  • The number of edges occurring to a vertex in a graph is its degree.
  • The total number of outgoing edges is the out-degree of a vertex in a directed graph, while the total number of receiving edges is the in-degree.
  • A source vertex is an in-degree zero, while a sink vertex is a vertex without-degree zero.
  • A vertex of degree zero that is not an edge's endpoint is called an isolated vertex.
  • Each edge has two ends, called vertices, to which it is connected.
  • A cycle is defined as a journey that begins and finishes simultaneously.
  • A path with distinct vertices is known as a simple path.
  • For any pair of vertices u, v, a graph is Strongly Connected if it accommodates a directed path from u to v and a directed path from v to u.
  • When undirected edges replace the directed edges in a directed graph, the Graph becomes connected (undirected). A weakly linked graph's vertices have at least one out-degree or in-degree.
  • The largest connected subgraph of an unconnected graph is called a connected component.
  • A bridge is an edge that, if removed, would cause the Graph to be disconnected.
  • Forest is a graph that does not have any cycles.
  • A tree is a linked graph that does not have any cycles. When all the cycles in a DAG (Directed Acyclic Graph) are removed, it becomes a tree, and when an edge in a tree is removed, it becomes a forest.
  • The spanning tree of an undirected graph is a subgraph that contains all of the Graph's vertices.

After learning about graph terminologies, we'll look at different graph representations in further depth.

Representation Of Graph in C#

In graph theory, a graph representation stores a graph in a computer's memory.

The collection of vertices and the neighbors of each vertex are required to represent a graph (vertices that are directly connected to it by an edge). The weight will be assigned to each edge if the Graph is weighted.

Depending on the density of the Graph's edges, the type of operations to be performed, and the simplicity of usage, there are several ways to describe it optimally.

  • Adjacency Matrix Representation
  • Adjacency List Representation

Adjacency Matrix Representation

A square matrix represents a finite graph as an adjacency matrix. The matrix's elements show whether two vertices in the Graph are adjacent or not. The adjacency matrix for a basic unweighted graph with vertex set V is a square |V| |V| matrix A with the element:

When an edge is formed between vertex i to vertex j, Aij = 1, and there isn't Aij = 0.

Each column in the matrix represents destination vertices, while each row represents source vertices. Because edges from a vertex to itself, i.e., loops, are not allowed in simple graphs, the diagonal members of the matrix are all 0. The adjacency matrix will be symmetric if the Graph is undirected. Aij can also indicate edge weights in a weighted graph.

An adjacency matrix uses n*n space since it stores a value (1/0/edge-weight) for every pair of vertices, whether or not the edge exists. They can only be used effectively when the Graph is dense.

Adjancency-matrix-representation-of-graph.

Adjacency List Representation

Each vertex in the Graph is associated with a collection of its neighboring vertices or edges in an adjacency list form, i.e., each vertex keeps a list of adjacent vertices. There are many different ways to express an adjacency list depending on the implementation. This data format allows additional data to be stored on the vertices. However, it is only viable when the Graph has a few edges. The Graph is sparse, in other words.

Adjancency-list-representation-of-graph.

Following that, we'll see various graph operations in C#.

Operations on Graphs in C#

The succeeding is the operations you can perform on graphs in data structures:

  • Creating graphs
  • Insert vertex
  • Delete vertex
  • Insert edge 
  • Delete edge

You'll go over each operation one by one in detail:

Creating Graphs

A graph can be created using one of two methods:

1. Adjacency Matrix

The connection matrix, or adjacency matrix, of a basic labeled graph, is a matrix with rows and columns labeled by graph vertices and a 1 or 0 in position depending on whether they are adjacent or not.

2. Adjacency List 

An adjacency list, made up of unordered lists, represents a finite graph. Each unordered list within an adjacency list describes the set of neighbors of a specific vertex.

Insert Vertex

When you add or insert a vertex to a graph after adding one or more vertices or nodes, the Graph increases by one, increasing the row and column sizes of the matrix.

insert-vertex-operations-on-graph-graphs

Delete Vertex

The term "delete a vertex" refers to the act of removing a specific node or vertex from a previously saved graph. The matrix returns a removed node if it appears in the Graph. The matrix returns the node not available if a deleted node does not appear in the Graph.

delete-vertex-operations-on-graph

Insert Edge 

An edge can be added to a graph by connecting two supplied vertices.

insert-edge-operations-on-graph-graphs

Delete Edge

An edge can be deleted by removing the connection between the vertices or nodes.

elete-edge-operations-on-graph-

After that, we'll look at two distinct sorts of graph traversal.

Learn Essential Skills for Effective Leadership

Executive Leadership Principles ProgramExplore Program
Learn Essential Skills for Effective Leadership

Graph Traversal in C#

A search approach for identifying a vertex in a graph is graph traversal. Graph traversal is also used in the search process to decide the order in which vertices are visited. A graph traversal finds the edges used in the search process without creating loops. That is, we can visit all of the Graph's vertices without walking through a looping path via graph traversal.

There are two techniques for traversing graphs, which are as follows.

  • DFS (Depth First Search)
  • BFS (Breadth-First Search)

DFS (Depth First Search)

A spanning tree is the result of a DFS traversal of a graph. A graph with no loops is known as a spanning tree. We use a Stack data structure with a maximum size equal to the number of vertices in the Graph to implement DFS traversal.

To implement DFS traversal, we take the following stages.

Step 1: Create a Stack with the number of vertices in the Graph as the size.

Step 2: Select any vertex as the traversal's beginning point. Please pay a visit to that vertex and add it to the Stack.

Step 3: Push any of the non-visited adjacent vertices of a vertex at the top of the Stack to the top of the Stack.

Step 4: Repeat steps 3 and 4 up to there are no additional vertices to visit from the vertex at the top of the Stack.

Step 5: If there are no new vertices to visit, go back and pop one from the Stack using backtracking.

Step 6: Continue using steps 3, 4, and 5 until the Stack is empty.

Step 7: When the Stack is empty, create the final spanning tree by deleting the Graph's unused edges.

Example

Let's see an example of how the Depth First Search algorithm works. An undirected graph with five vertices is used.

graph-traversal-depth-firts-search

Starting with vertex 1, the DFS method places it in the Visited list and adds its neighboring vertices to the Stack.

graph-traversal-depth-firts-search

Next, we visit the top of the Stack, element 2, and nearby nodes. We go to 3 instead of 1 because one has already been visited.

graph-traversal-depth-firts-search2

We add vertex 3 to the top of the Stack and visit it because it has an unvisited adjacent vertex in 5.

graph-traversal-depth-firts-search4

-traversal-depth-firts-search

We have finished the Depth First Search Traversal of the Graph after visiting the last element 4, which has no unvisited nearby nodes.

graph-traversal-depth-firts-search5

Code Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace DFS1

{

    class Graph

    {

        private int _v;    

        private bool _direct;

        LinkedList<int>[] _adj;        

        public Graph (int v, bool direct)

        {

            _adj = new LinkedList<int>[v];

            for (int i = 0; i < _adj.Length; i++)

            {

                _adj[i] = new LinkedList<int>();

            }

            _v = v;

            _direct = direct;       

        }

        public void Add_Edge(int v, int w)

        {            

            _adj[v].AddLast(w);

            if (!_direct)

            {

                _adj[w].AddLast(v);

            }

        }

        public void DepthFirstSearch(int v)

        {

            // Mark all the vertices as not visited

            bool[] visit = new bool[_v];    

            for (int i = 0; i < _v; i++)

                visit[i] = false; 

            // Call the recursive function to print DFS traversal

            DFStil(v, visit);          

        }

        private void DFStil(int v, bool []visit)

        {

            // Mark the current node as visited and display it

            visit[v] = true;

            Console.Write( v + " " ); 

            // Recur for all the vertices adjacent to this vertex

            LinkedList<int> list = _adj[v];

            foreach (var value in list)

            {

                if (!visit[value])

                    DFStil(value, visit);

            }

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Graph gr = new Graph(7, true);

            gr.Add_Edge(0, 1);

            gr.Add_Edge(0, 2);

            gr.Add_Edge(0, 3);

            gr.Add_Edge(1, 0);

            gr.Add_Edge(1, 5);

            gr.Add_Edge(2, 5);

            gr.Add_Edge(3, 0);

            gr.Add_Edge(3, 4);

            gr.Add_Edge(4, 6);

            gr.Add_Edge(5, 1);

            gr.Add_Edge(6, 5);   

            Console.Write("Depth First Traversal from vertex 2:\n");

            gr.DepthFirstSearch(2);

        }

    }

}

Output 

depth-first-search-code-output

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

BFS (Breadth-First Search)

The outcome of a BFS traversal of a graph is a spanning tree. A spanning tree is a graph that is devoid of loops. To implement BFS traversal, we utilize a Queue data structure with a maximum size equal to the number of vertices in the Graph.

To build BFS traversal, we apply the steps below.

Step 1: Create a Queue with a size equal to the number of vertices in the Graph.

Step 2: Choose any vertex as the traversal's beginning point. Make a trip to that vertex and add it to the Queue.

Step 3: Insert all of the non-visited adjacent vertices of the vertex at the front of the Queue into the Queue.

Step 4: Delete the vertex in front of the Queue if no new vertex has to be visited.

Step 5: Continue using steps 3 and 4 until the Queue is empty.

Step 6: When the Queue is empty, create the final spanning tree by eliminating the Graph's unused edges.

Let's look at an illustration of how the Breadth-First Search algorithm works. An undirected graph with five vertices is used.

graph-traversal-breadth-firts-search.

Starting with vertex 1, the BFS algorithm places it in the Visited list and adds its neighboring vertices to the Stack.

graph-traversal-breadth-firts-search1.

Following that, we go to the element at the front of the Queue, i.e., 2, and its nearby nodes. We go to 3 instead of 1 because one has already been visited.

graph-traversal-breadth-firts-search2

We move vertex 3 to the back of the Queue and visit 4, which is at the front because it has an unvisited adjacent vertex in 5.

-graph-traversal-breadth-firts-search3.

graph-traversal-breadth-firts-search

Since the sole adjacent node of 4, namely 1, has already been accessed, only five remain in the Queue. We go there.

graph-traversal-breadth-firts-search4

Code Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace BreadthFirstSearch

{

    class Graph

    {

        private int _v;    

        private bool _direct;

        LinkedList<int>[] _adj;       

        public Graph (int v, bool direct)

        {

            _adj = new LinkedList<int>[v];

            for (int i = 0; i < _adj.Length; i++)

            {

                _adj[i] = new LinkedList<int>();

            }

            _v = v;

            _direct = direct;       

        }

        public void Add_Edge(int v, int w)

        {            

            _adj[v].AddLast(w);

            if (!_direct)

            {

                _adj[w].AddLast(v);

            }

        }

        public void BreadthFirstSearch(int s)

        {

            bool[] visited = new bool[_v];

            for(int i = 0; i < _v; i++)

                visited[i] = false;  

            // Create a queue for BFS

            LinkedList<int> queue1 = new LinkedList<int>();   

            visited[s] = true;

            queue1.AddLast(s);             

            while(queue1.Any())

            {

                // Dequeue a vertex from queue and print it

                s = queue1.First();

                Console.Write( s + " " );

                queue1.RemoveFirst();

                LinkedList<int> list = _adj[s];

                foreach (var value in list)                

                {

                    if (!visited[val])

                    {

                        visited[val] = true;

                        queue1.AddLast(val);

                    }

                }

            }

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Graph gr = new Graph(7, true);

            gr.Add_Edge(0, 1);

            gr.Add_Edge(0, 2);

            gr.Add_Edge(0, 3);

            gr.Add_Edge(1, 0);

            gr.Add_Edge(1, 5);

            gr.Add_Edge(2, 5);

            gr.Add_Edge(3, 0);

            gr.Add_Edge(3, 4);

            gr.Add_Edge(4, 6);

            gr.Add_Edge(5, 1);

            gr.Add_Edge(6, 5);  

            Console.Write("Breadth First Traversal from vertex 2:\n");

            gr.BreadthFirstSearch(2);

        }

    }

}

Output

breadth-first-search-code-output.

Last but not least, we'll look at various graph applications in the graphs in the c# article.

Prepare Yourself to Answer All Questions!

Automation Testing Masters ProgramExplore Program
Prepare Yourself to Answer All Questions!

Applications of Graphs in C#

The applications of graphs in real life are listed below.

1. Facebook's Graph API

The Graph API on Facebook is likely the best example of graphs used to solve real-world problems. The Graph API is a game-changer for large-scale data delivery.

Everything is a vertice or node in the Graph API. Users, Pages, Places, Groups, Comments, Photos, Photo Albums, Stories, Videos, Notes, Events, and so on are examples of this. A vertice is anything that has data-storing properties.

And every link or interaction is a vantage point. This may be something like a user uploading a photo, video, or comment, or a user updating their profile with their birthplace, relationship status, or a friend's photo, among other things.

2. Google's Knowledge Graph

A knowledge graph is defined as a graph-based representation of knowledge that connects data and graphs. It is still unclear what it can and cannot achieve.

3. Yelp's Local Graph

The Local Graph API claims to make it easy for developers to incorporate Yelp's data into their products and share amazing local companies.

By describing the business problem as a graph within its schema, GraphQL takes advantage of the capabilities of graph data structures.

GraphQL is most commonly used to manipulate graph data structures. Both the Apollo Client and Relay use GraphQL data in a normalized graph.

4. Path Optimizing Algorithm

Path optimizations are generally concerned with determining the optimum link that meets a set of predetermined criteria, such as speed, safety, and fuel consumption, or a combination of criteria, such as procedures and routes.

The Shortest Path of a graph in an unweighted graph is the path with the fewest edges. Breadth-First Search (BFS) is used to locate the shortest paths in graphs—with breadth graph traversals; we always reach a node from another node with the fewest number of edges.

Using either BFS or Depth First Search, any Spanning Tree is a Minimum Spanning Tree unweighted graph.

5. Google Map Platform

Shortest Path APIs like Google Maps and Routes are classics. Using edge-weighted directed graphs (digraphs), this is an easy graph problem to answer using edge-weighted directed graphs (digraphs).

The goal of a Map API is to discover the shortest way from your current location to any other destination on the map, as in a single source shortest path variant.

6. Flight Networks

In the case of aircraft networks, efficient route optimizations suit graph data structures perfectly. Airport procedures can be efficiently modeled and optimized using graph models.

Algorithm engineering is used to determine the optimal connections in aviation networks.

Graph data structures are employed in-flight networks to compute shortest pathways and fuel usage in route planning, commonly done in a multi-modal setting.

Now, in the graphs in c#, we'll summarize all of the subjects we've studied thus far in this post.

Next Steps

We grasped everything there is to know about graphs in this c# tutorial, as well as certain sorts of graphs and graph terminologies. Later on, we observed two types of graph representation: adjacency matrix and list and a variety of graph operations. Then there are two types of graph traversal: depth-first and breadth-first, and finally, there are some graph applications in the real world.

This is the path for you if you want to go beyond Mobile and Software Development and gain knowledge of the most in-demand programming languages and skills today. In that case, Simplilearn's Post Graduate Program in Full Stack Web Development Course is a good fit. Look into this well-known Bootcamp program for more information.

Do you have any questions about these Graphs in C#? Please leave them in the comments segment at the bottom of this article if you do. Our experts will gladly respond to your questions as soon as possible!

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.