count edges in a graph in csharp

To count the number of edges in a graph in C#, we first need to represent the graph in our code. One way to do this is to use an adjacency matrix or adjacency list.

Here is an example implementation using an adjacency matrix:

main.cs
// initialize graph as a 2D array
int[,] graph = new int[,]
{
    {0, 1, 1, 0, 0},
    {1, 0, 1, 1, 0},
    {1, 1, 0, 1, 1},
    {0, 1, 1, 0, 1},
    {0, 0, 1, 1, 0},
};

// count number of edges by iterating through upper triangle of matrix
int numEdges = 0;
for (int i = 0; i < graph.GetLength(0); i++)
{
    for (int j = i + 1; j < graph.GetLength(1); j++)
    {
        if (graph[i,j] == 1)
        {
            numEdges++;
        }
    }
}

Console.WriteLine("Number of edges: " + numEdges);
499 chars
25 lines

In this example, we initialize the graph as a 2D array where each element represents an edge in the graph. A value of 1 at index [i,j] indicates that there is an edge between vertices i and j.

We then iterate through the upper triangle of the matrix and count the number of edges by checking if the value is 1. Since our graph is undirected, we only need to iterate through the upper triangle to avoid double-counting edges.

The output will be the total number of edges in the graph.

gistlibby LogSnag