Minimum number of edges that need to be added to form a triangle

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.

Examples:

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:



  1. 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.
  2. 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).
  3. Case 3: Otherwise, if there only a single pair of vertices is connected then ans = min(ans, 2).
  4. 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.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the minimum number
// of edges that need to be added to
// the given graph such that it
// contains at least one triangle
int minEdges(vector<pair<int, int> > v, int n)
{
  
    // adj is the adjacency matrix such that
    // adj[i][j] = 1 when there is an
    // edge between i and j
    vector<vector<int> > adj;
    adj.resize(n + 1);
    for (int i = 0; i < adj.size(); i++)
        adj[i].resize(n + 1, 0);
  
    // As the graph is undirected
    // so there will be an edge
    // between (i, j) and (j, i)
    for (int i = 0; i < v.size(); i++) {
        adj[v[i].first][v[i].second] = 1;
        adj[v[i].second][v[i].first] = 1;
    }
  
    // To store the required
    // count of edges
    int edgesNeeded = 3;
  
    // For every possible vertex triplet
    for (int i = 1; i <= n; i++) {
        for (int j = i + 1; j <= n; j++) {
            for (int k = j + 1; k <= n; k++) {
  
                // If the vertices form a triangle
                if (adj[i][j] && adj[j][k] && adj[k][i])
                    return 0;
  
                // If no edges are present
                if (!(adj[i][j] || adj[j][k] || adj[k][i]))
                    edgesNeeded = min(edgesNeeded, 3);
  
                else {
  
                    // If only 1 edge is required
                    if ((adj[i][j] && adj[j][k])
                        || (adj[j][k] && adj[k][i])
                        || (adj[k][i] && adj[i][j])) {
                        edgesNeeded = 1;
                    }
  
                    // Two edges are required
                    else
                        edgesNeeded = min(edgesNeeded, 2);
                }
            }
        }
    }
    return edgesNeeded;
}
  
// Driver code
int main()
{
  
    // Number of nodes
    int n = 3;
  
    // Storing the edges in a vector of pairs
    vector<pair<int, int> > v = { { 1, 2 }, { 1, 3 } };
  
    cout << minEdges(v, n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.io.*;
import java.util.*;
  
class Pair<V, E> 
{
    V first;
    E second;
  
    Pair(V first, E second) 
    {
        this.first = first;
        this.second = second;
    }
}
  
class GFG 
{
  
    // Function to return the minimum number
    // of edges that need to be added to
    // the given graph such that it
    // contains at least one triangle
    static int minEdges(Vector<Pair<Integer, 
                                    Integer>> v, int n) 
    {
  
        // adj is the adjacency matrix such that
        // adj[i][j] = 1 when there is an
        // edge between i and j
        int[][] adj = new int[n + 1][n + 1];
  
        // As the graph is undirected
        // so there will be an edge
        // between (i, j) and (j, i)
        for (int i = 0; i < v.size(); i++) 
        {
            adj[v.elementAt(i).first]
               [v.elementAt(i).second] = 1;
            adj[v.elementAt(i).second]
               [v.elementAt(i).first] = 1;
        }
  
        // To store the required
        // count of edges
        int edgesNeeded = 0;
  
        // For every possible vertex triplet
        for (int i = 1; i <= n; i++)
        {
            for (int j = i + 1; j <= n; j++) 
            {
                for (int k = j + 1; k <= n; k++) 
                {
  
                    // If the vertices form a triangle
                    if (adj[i][j] == 1 && 
                        adj[j][k] == 1 && adj[k][i] == 1)
                        return 0;
  
                    // If no edges are present
                    if (!(adj[i][j] == 1 || 
                          adj[j][k] == 1 || adj[k][i] == 1))
                        edgesNeeded = Math.min(edgesNeeded, 3);
  
                    else 
                    {
  
                        // If only 1 edge is required
                        if ((adj[i][j] == 1 && adj[j][k] == 1) || 
                            (adj[j][k] == 1 && adj[k][i] == 1) || 
                            (adj[k][i] == 1 && adj[i][j] == 1)) 
                        {
                            edgesNeeded = 1;
                        }
  
                        // Two edges are required
                        else
                            edgesNeeded = Math.min(edgesNeeded, 2);
                    }
                }
            }
        }
        return edgesNeeded;
    }
  
    // Driver Code
    public static void main(String[] args) 
    {
  
        // Number of nodes
        int n = 3;
  
        // Storing the edges in a vector of pairs
        Vector<Pair<Integer, 
                    Integer>> v = new Vector<>(Arrays.asList(new Pair<>(1, 2), 
                                                             new Pair<>(1, 3)));
  
        System.out.println(minEdges(v, n));
    }
}
  
// This code is contributed by
// sanjeev2552

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach 
  
# Function to return the minimum number 
# of edges that need to be added to 
# the given graph such that it 
# contains at least one triangle 
def minEdges(v, n) : 
  
    # adj is the adjacency matrix such that 
    # adj[i][j] = 1 when there is an 
    # edge between i and j 
    adj = dict.fromkeys(range(n + 1)); 
      
    # adj.resize(n + 1); 
    for i in range(n + 1) :
        adj[i] = [0] * (n + 1); 
  
    # As the graph is undirected 
    # so there will be an edge 
    # between (i, j) and (j, i) 
    for i in range(len(v)) :
        adj[v[i][0]][v[i][1]] = 1
        adj[v[i][1]][v[i][0]] = 1
  
    # To store the required 
    # count of edges 
    edgesNeeded = 3
  
    # For every possible vertex triplet 
    for i in range(1, n + 1) : 
        for j in range(i + 1, n + 1) :
            for k in range(j + 1, n + 1) :
  
                # If the vertices form a triangle 
                if (adj[i][j] and adj[j][k] and adj[k][i]) :
                    return 0
  
                # If no edges are present 
                if (not (adj[i][j] or adj[j][k] or adj[k][i])) :
                    edgesNeeded = min(edgesNeeded, 3); 
  
                else :
  
                    # If only 1 edge is required 
                    if ((adj[i][j] and adj[j][k])
                        or (adj[j][k] and adj[k][i]) 
                        or (adj[k][i] and adj[i][j])) : 
                        edgesNeeded = 1
  
                    # Two edges are required 
                    else :
                        edgesNeeded = min(edgesNeeded, 2); 
      
    return edgesNeeded; 
  
# Driver code 
if __name__ == "__main__"
  
    # Number of nodes 
    n = 3
  
    # Storing the edges in a vector of pairs 
    v = [ [ 1, 2 ], [ 1, 3 ] ]; 
  
    print(minEdges(v, n)); 
      
# This code is contributed by kanugargng

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;
using System.Collections.Generic;
  
class Pair 
{
    public int first;
    public int second;
  
    public Pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }
}
  
class GFG 
{
  
    // Function to return the minimum number
    // of edges that need to be added to
    // the given graph such that it
    // contains at least one triangle
    static int minEdges(List<Pair> v, int n) 
    {
  
        // adj is the adjacency matrix such that
        // adj[i,j] = 1 when there is an
        // edge between i and j
        int[,] adj = new int[n + 1, n + 1];
  
        // As the graph is undirected
        // so there will be an edge
        // between (i, j) and (j, i)
        for (int i = 0; i < v.Count; i++) 
        {
            adj[v[i].first,v[i].second] = 1;
            adj[v[i].second,v[i].first] = 1;
        }
  
        // To store the required
        // count of edges
        int edgesNeeded = 0;
  
        // For every possible vertex triplet
        for (int i = 1; i <= n; i++)
        {
            for (int j = i + 1; j <= n; j++) 
            {
                for (int k = j + 1; k <= n; k++) 
                {
  
                    // If the vertices form a triangle
                    if (adj[i, j] == 1 && 
                        adj[j, k] == 1 && adj[k, i] == 1)
                        return 0;
  
                    // If no edges are present
                    if (!(adj[i, j] == 1 || 
                        adj[j, k] == 1 || adj[k, i] == 1))
                        edgesNeeded = Math.Min(edgesNeeded, 3);
  
                    else
                    {
  
                        // If only 1 edge is required
                        if ((adj[i, j] == 1 && adj[j, k] == 1) || 
                            (adj[j, k] == 1 && adj[k, i] == 1) || 
                            (adj[k, i] == 1 && adj[i, j] == 1)) 
                        {
                            edgesNeeded = 1;
                        }
  
                        // Two edges are required
                        else
                            edgesNeeded = Math.Min(edgesNeeded, 2);
                    }
                }
            }
        }
        return edgesNeeded;
    }
  
    // Driver Code
    public static void Main(String[] args) 
    {
  
        // Number of nodes
        int n = 3;
  
        // Storing the edges in a vector of pairs
          
        List<Pair> v = new List<Pair>();
        v.Add(new Pair(1, 2));
        v.Add(new Pair(1, 3));
        Console.WriteLine(minEdges(v, n));
    }
}
  
// This code is contributed by PrinciRaj1992

chevron_right


Output:

1



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.