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.
- Maximum number of edges to be added to a tree so that it stays a Bipartite graph
- Minimum edges to be added in a directed graph so that any node can be reachable from a given node
- Maximum edges that can be added to DAG so that is remains DAG
- Minimum number of edges between two vertices of a graph using DFS
- Minimum number of edges between two vertices of a Graph
- Minimum number to be added to all digits of X to make X > Y
- Minimum cost to form a number X by adding up powers of 2
- Form lexicographically smallest string with minimum replacements having equal number of 0s, 1s and 2s
- Dijkstra's shortest path with minimum edges
- Minimum edges required to add to make Euler Circuit
- Remove all outgoing edges except edge with minimum weight
- Find the minimum spanning tree with alternating colored edges
- Minimum edges to reverse to make path from a source to a destination
- Minimum cost to reverse edges such that there is path between every pair of nodes
- Ways to Remove Edges from a Complete Graph to make Odd Edges
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.