Given an Undirected simple graph, We need to find how many triangles it can have. For example below graph have 2 triangles in it.
Let A be adjacency matrix representation of graph. If we calculate A3, then the number of triangle in Undirected Graph is equal to trace(A3) / 6. Where trace(A) is the sum of the elements on the main diagonal of matrix A.
Trace of a graph represented as adjacency matrix A[V][V] is, trace(A[V][V]) = A + A + .... + A[V-1][V-1] Count of triangles = trace(A3) / 6
Below is implementation of above formula.
Total number of Triangle in Graph : 2
How does this work?
If we compute An for an adjacency matrix representation of graph, then a value An[i][j] represents number of distinct walks between vertex i to j in graph. In A3, we get all distinct paths of length 3 between every pair of vertices.
A triangle is a cyclic path of length three, i.e. begins and ends at same vertex. So A3[i][i] represents a triangle beginning and ending with vertex i. Since a triangle has three vertices and it is counted for every vertex, we need to divide result by 3. Furthermore, since the graph is undirected, every triangle twice as i-p-q-j and i-q-p-j, so we divide by 2 also. Therefore, number of triangles is trace(A3) / 6.
The time complexity of above algorithm is O(V3) where V is number of vertices in the graph, we can improve the performance to O(V2.8074) using Strassen’s matrix multiplication algorithm.
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Number of Triangles in Directed and Undirected Graphs
- Check whether a given graph is Bipartite or not
- Snake and Ladder Problem
- Count all possible walks from a source to a destination with exactly k edges
- Minimum time required to rot all oranges
- Print all Jumping Numbers smaller than or equal to a given value
- Connected Components in an undirected graph
- Maximum Bipartite Matching
- Detect Cycle in a Directed Graph
- Boggle (Find all possible words in a board of characters) | Set 1
- Prim’s MST for Adjacency List Representation | Greedy Algo-6
- Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
- Number of groups formed in a graph of friends
- Hamiltonian Cycle | Backtracking-6
- Floyd Warshall Algorithm | DP-16
Improved By : vt_m