// C# program to count triangles in a graph.
// The program is for adjacency matrix
// representation of the graph.
using System;
class GFG {
// Number of vertices in the graph
const int V = 4;
// function to calculate the
// number of triangles in a
// simple directed/undirected
// graph. isDirected is true if
// the graph is directed, its
// false otherwise
static int countTriangle(int[, ] graph, bool isDirected)
{
// Initialize result
int count_Triangle = 0;
// Consider every possible
// triplet of edges in graph
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
for (int k = 0; k < V; k++)
{
// check the triplet if
// it satisfies the condition
if (graph[i, j] != 0
&& graph[j, k] != 0
&& graph[k, i] != 0)
count_Triangle++;
}
}
}
// if graph is directed ,
// division is done by 3,
// else division by 6 is done
if (isDirected != false)
count_Triangle = count_Triangle / 3;
else
count_Triangle = count_Triangle / 6;
return count_Triangle;
}
// Driver code
static void Main()
{
// Create adjacency matrix
// of an undirected graph
int[, ] graph = new int[4, 4] { { 0, 1, 1, 0 },
{ 1, 0, 1, 1 },
{ 1, 1, 0, 1 },
{ 0, 1, 1, 0 } };
// Create adjacency matrix
// of a directed graph
int[, ] digraph = new int[4, 4] { { 0, 0, 1, 0 },
{ 1, 0, 0, 1 },
{ 0, 1, 0, 0 },
{ 0, 0, 1, 0 } };
Console.Write("The Number of triangles"
+ " in undirected graph : "
+ countTriangle(graph, false));
Console.Write("\n\nThe Number of "
+ "triangles in directed graph : "
+ countTriangle(digraph, true));
}
}
// This code is contributed by anuj_67