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.
- Minimum number of Edges to be added to a Graph to satisfy the given condition
- Minimum edges to be added in a directed graph so that any node can be reachable from a given node
- Maximum number of edges to be added to a tree so that it stays a Bipartite graph
- Ways to Remove Edges from a Complete Graph to make Odd Edges
- Maximum edges that can be added to DAG so that is remains DAG
- Maximum number of edges that N-vertex graph can have such that graph is Triangle free | Mantel's Theorem
- Minimum number of edges between two vertices of a Graph
- Minimum number of edges between two vertices of a graph using DFS
- Minimum number to be added to all digits of X to make X > Y
- Minimum edges to reverse to make path from a source to a destination
- Minimum edges required to add to make Euler Circuit
- Remove all outgoing edges except edge with minimum weight
- Dijkstra's shortest path with minimum edges
- Minimum cost to reverse edges such that there is path between every pair of nodes
- Find the minimum spanning tree with alternating colored edges
- Minimum colors required such that edges forming cycle do not have same color
- Path with minimum XOR sum of edges in a directed graph
- Minimum edges required to make a Directed Graph Strongly Connected
- Minimum elements to be added in a range so that count of elements is divisible by K
- Count number of edges in an undirected graph
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.