Given an undirected graph with N vertices and N edges. No two edges connect the same pair of vertices. A triangle is a set of three distinct vertices such that each pair of those vertices is connected by an edge i.e. three distinct vertices u, v and w are a triangle if the graph contains the edges (u, v), (v, w) and (v, u).
The task is to find the minimum number of edges needed to be added to the given graph such that the graph contains at least one triangle.
Input: 1 / \ 2 3 Output: 1 Input: 1 3 / / 2 4 Output: 2
Approach: Initialize ans = 3 which is the maximum count of edges required to form a triangle. Now, for every possible vertex triplet there are four cases:
- Case 1: If there exist nodes i, j and k such that there is an edge from (i, j), (j, k) and (k, i) then the answer is 0.
- Case 2: If there exist nodes i, j and k such that only two pairs of vertices are connected then a single edge is required to form a triangle. So update ans = min(ans, 1).
- Case 3: Otherwise, if there only a single pair of vertices is connected then ans = min(ans, 2).
- Case 4: When there is no edge then ans = min(ans, 3).
Print the ans in the end.
Below is the implementation of the above approach.