Given an undirected graph with N vertices and K edges, the task is to check if for every combination of three vertices in the graph, there exists two vertices which are connected to third vertex. In other words, for every vertex triplet (a, b, c), if there exists a path between a and c, then there should also exist a path between b and c.
Examples:
Input: N = 4, K = 3
Edges: 1 -> 2, 2 -> 3, 3 -> 4
Output: YES
Explanation:
Since the whole graph is connected, the above condition will always be valid.Input: N = Â 5 and K = 3
Edges: 1 -> 3, 3 -> 4, 2 -> 5.
Output: NO
Explanation:Â
If we consider the triplet (1, 2, 3) then there is a path between vertices 1 and 3 but there is no path between vertices 2 and 3.
Approach: Follow the steps below to solve the problem –
- Traverse the graph by DFS Traversal technique from any component and maintain two variables to store the component minimum and component maximum.
- Store every component maximum and minimum in a vector.
- Now, if any two components have an intersection in their minimum and maximum values interval, then there will exist a valid (a < b < c) triplet. Hence, both of the components should be connected. Otherwise, the graph is not valid.
Below is the implementation of the above approach
C++
// C++ program of the // above approach Â
#include <bits/stdc++.h> using namespace std; Â
// Function to add edge into // the graph void addEdge(vector< int > adj[], Â Â Â Â Â Â Â Â Â Â Â Â Â int u, int v) { Â Â Â Â adj[u].push_back(v); Â Â Â Â adj[v].push_back(u); } Â
void DFSUtil( int u, vector< int > adj[], Â Â Â Â Â Â Â Â Â Â Â Â Â vector< bool >& visited, Â Â Â Â Â Â Â Â Â Â Â Â Â int & componentMin, Â Â Â Â Â Â Â Â Â Â Â Â Â int & componentMax) { Â Â Â Â visited[u] = true ; Â
    // Finding the maximum and     // minimum values in each component     componentMax = max(componentMax, u);     componentMin = min(componentMin, u); Â
    for ( int i = 0; i < adj[u].size(); i++)         if (visited[adj[u][i]] == false )             DFSUtil(adj[u][i], adj, visited,                     componentMin, componentMax); } Â
// Function for checking whether // the given graph is valid or not bool isValid(vector<pair< int , int > >& v) {     int MAX = -1;     bool ans = 0;     // Checking for intersecting intervals     for ( auto i : v) {         // If intersection is found         if (i.first <= MAX) { Â
            // Graph is not valid             ans = 1;         } Â
        MAX = max(MAX, i.second);     } Â
    return (ans == 0 ? 1 : 0); } Â
// Function for the DFS Traversal void DFS(vector< int > adj[], int V) {     std::vector<pair< int , int > > v;     // Traversing for every vertex     vector< bool > visited(V, false );     for ( int u = 1; u <= V; u++) {         if (visited[u] == false ) {             int componentMax = u;             int componentMin = u; Â
            DFSUtil(u, adj, visited,                     componentMin, componentMax); Â
            // Storing maximum and minimum             // values of each component             v.push_back({ componentMin,                           componentMax });         }     } Â
    bool check = isValid(v); Â
    if (check)         cout << "Yes" ;     else         cout << "No" ; Â
    return ; } Â
// Driver code int main() { Â Â Â Â int N = 4, K = 3; Â
    vector< int > adj[N + 1]; Â
    addEdge(adj, 1, 2);     addEdge(adj, 2, 3);     addEdge(adj, 3, 4); Â
    DFS(adj, N); Â
    return 0; } |
Java
// Java program of the // above approach import java.util.*; import java.lang.*; Â
class GFG{ Â Â Â Â Â static class pair { Â Â Â Â int first, second; Â Â Â Â pair( int first, int second) Â Â Â Â { Â Â Â Â Â Â Â Â this .first = first; Â Â Â Â Â Â Â Â this .second = second; Â Â Â Â } } Â
// Function to add edge into // the graph static void addEdge(ArrayList<ArrayList<Integer>> adj, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int u, int v) { Â Â Â Â adj.get(u).add(v); Â Â Â Â adj.get(v).add(u); } Â
static void DFSUtil( int u, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ArrayList<ArrayList<Integer>> adj, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â boolean [] visited, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int componentMin, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int componentMax) { Â Â Â Â visited[u] = true ; Â
    // Finding the maximum and     // minimum values in each component     componentMax = Math.max(componentMax, u);     componentMin = Math.min(componentMin, u); Â
    for ( int i = 0 ; i < adj.get(u).size(); i++)         if (visited[adj.get(u).get(i)] == false )             DFSUtil(adj.get(u).get(i), adj, visited,                     componentMin, componentMax); } Â
// Function for checking whether // the given graph is valid or not static boolean isValid(ArrayList<pair> v) {     int MAX = - 1 ;     boolean ans = false ;          // Checking for intersecting intervals     for (pair i : v)     {                  // If intersection is found         if (i.first <= MAX)         {                          // Graph is not valid             ans = true ;         }         MAX = Math.max(MAX, i.second);     }     return (ans == false ? true : false ); } Â
// Function for the DFS Traversal static void DFS(ArrayList<ArrayList<Integer>> adj,                 int V) {    ArrayList<pair> v = new ArrayList<>();        // Traversing for every vertex    boolean [] visited = new boolean [V + 1 ];         for ( int u = 1 ; u <= V; u++)     {         if (visited[u] == false )         {             int componentMax = u;             int componentMin = u; Â
            DFSUtil(u, adj, visited,                     componentMin,                     componentMax); Â
            // Storing maximum and minimum             // values of each component             v.add( new pair(componentMin,                            componentMax));         }     } Â
    boolean check = isValid(v); Â
    if (check)         System.out.println( "Yes" );     else         System.out.println( "No" ); Â
    return ; } Â
// Driver code public static void main (String[] args) { Â Â Â Â int N = 4 , K = 3 ; Â Â Â Â Â Â Â Â Â ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); Â Â Â Â Â Â Â Â Â for ( int i = 0 ; i <= N + 1 ; i++) Â Â Â Â Â Â Â Â adj.add( new ArrayList<>()); Â Â Â Â Â Â Â Â Â addEdge(adj, 1 , 2 ); Â Â Â Â addEdge(adj, 2 , 3 ); Â Â Â Â addEdge(adj, 3 , 4 ); Â Â Â Â Â Â Â Â Â DFS(adj, N); } } Â
// This code is contributed by offbeat |
Python3
# Python3 program of the # above approach Â
# Function to add edge into # the graph def addEdge(adj, u, v): Â
    adj[u].append(v)     adj[v].append(u)     return adj Â
def DFSUtil(u, adj, visited, Â Â Â Â Â Â Â Â Â Â Â Â componentMin, componentMax): Â
    visited[u] = True Â
    # Finding the maximum and     # minimum values in each component     componentMax = max (componentMax, u)     componentMin = min (componentMin, u) Â
    for i in range ( len (adj[u])):         if (visited[adj[u][i]] = = False ):             visited, componentMax, componentMin = DFSUtil(                 adj[u][i], adj, visited, componentMin,                 componentMax)                  return visited, componentMax, componentMin Â
# Function for checking whether # the given graph is valid or not def isValid(v): Â
    MAX = - 1     ans = False Â
    # Checking for intersecting intervals     for i in v:         if len (i) ! = 2 :             continue                  # If intersection is found         if (i[ 0 ] < = MAX ): Â
            # Graph is not valid             ans = True Â
        MAX = max ( MAX , i[ 1 ]) Â
    return ( True if ans = = False else False ) Â
# Function for the DFS Traversal def DFS(adj, V): Â
    v = [[]]          # Traversing for every vertex     visited = [ False for i in range (V + 1 )]          for u in range ( 1 , V + 1 ):         if (visited[u] = = False ):             componentMax = u             componentMin = u Â
            visited, componentMax, componentMin = DFSUtil(                 u, adj, visited, componentMin,                 componentMax) Â
            # Storing maximum and minimum             # values of each component             v.append([componentMin, componentMax]) Â
    check = isValid(v) Â
    if (check):         print ( 'Yes' )     else :         print ( 'No' ) Â
    return Â
# Driver code if __name__ = = "__main__" : Â
    N = 4     K = 3 Â
    adj = [[] for i in range (N + 1 )] Â
    adj = addEdge(adj, 1 , 2 )     adj = addEdge(adj, 2 , 3 )     adj = addEdge(adj, 3 , 4 ) Â
    DFS(adj, N) Â
# This code is contributed by rutvik_56 |
C#
// C# program of the // above approach using System; using System.Collections; using System.Collections.Generic;   class GFG{       class pair {     public int first, second;     public pair( int first, int second)     {         this .first = first;         this .second = second;     } }   // Function to add edge into // the graph static void addEdge(ArrayList adj,                     int u, int v) {     ((ArrayList)adj[u]).Add(v);     ((ArrayList)adj[v]).Add(u); }   static void DFSUtil( int u, ArrayList adj,                     bool [] visited,                     int componentMin,                     int componentMax) {     visited[u] = true ;       // Finding the maximum and     // minimum values in each component     componentMax = Math.Max(componentMax, u);     componentMin = Math.Min(componentMin, u);       for ( int i = 0; i < ((ArrayList)adj[u]).Count; i++)         if (visited[( int )((ArrayList)adj[u])[i]] == false )             DFSUtil(( int )((ArrayList)adj[u])[i], adj, visited,                     componentMin, componentMax); }   // Function for checking whether // the given graph is valid or not static bool isValid(ArrayList v) {     int MAX = -1;     bool ans = false ;           // Checking for intersecting intervals     foreach (pair i in v)     {                   // If intersection is found         if (i.first <= MAX)         {                           // Graph is not valid             ans = true ;         }         MAX = Math.Max(MAX, i.second);     }     return (ans == false ? true : false ); }   // Function for the DFS Traversal static void DFS(ArrayList adj,                 int V) {    ArrayList v = new ArrayList();         // Traversing for every vertex    bool [] visited = new bool [V + 1];          for ( int u = 1; u <= V; u++)     {         if (visited[u] == false )         {             int componentMax = u;             int componentMin = u;               DFSUtil(u, adj, visited,                     componentMin,                     componentMax);               // Storing maximum and minimum             // values of each component             v.Add( new pair(componentMin,                            componentMax));         }     }       bool check = isValid(v);       if (check)         Console.WriteLine( "Yes" );     else         Console.WriteLine( "No" );       return ; }   // Driver code public static void Main( string [] args) {     int N = 4;           ArrayList adj = new ArrayList();           for ( int i = 0; i <= N + 1; i++)         adj.Add( new ArrayList());           addEdge(adj, 1, 2);     addEdge(adj, 2, 3);     addEdge(adj, 3, 4);           DFS(adj, N); } } Â
// This code is contributed by pratham76 |
Javascript
<script> Â
// JavaScript program of the // above approach       class pair {     constructor(first, second)     {         this .first = first;         this .second = second;     } }   // Function to add edge into // the graph function addEdge(adj,u, v) {     (adj[u]).push(v);     (adj[v]).push(u); }   function DFSUtil(u, adj, visited, componentMin, componentMax) {     visited[u] = true ;       // Finding the maximum and     // minimum values in each component     componentMax = Math.max(componentMax, u);     componentMin = Math.min(componentMin, u);       for ( var i = 0; i < (adj[u]).length; i++)         if (visited[(adj[u])[i]] == false )             DFSUtil((adj[u])[i], adj, visited,                     componentMin, componentMax); }   // Function for checking whether // the given graph is valid or not function isValid(v) {     var MAX = -1;     var ans = false ;           // Checking for intersecting intervals     for ( var i of v)     {                   // If intersection is found         if (i.first <= MAX)         {                           // Graph is not valid             ans = true ;         }         MAX = Math.max(MAX, i.second);     }     return (ans == false ? true : false ); }   // Function for the DFS Traversal function DFS(adj, V) {    var v = [];         // Traversing for every vertex    var visited = Array(V+1).fill( false );          for ( var u = 1; u <= V; u++)     {         if (visited[u] == false )         {             var componentMax = u;             var componentMin = u;               DFSUtil(u, adj, visited,                     componentMin,                     componentMax);               // Storing maximum and minimum             // values of each component             v.push( new pair(componentMin,                            componentMax));         }     }       var check = isValid(v);       if (check)         document.write( "Yes" );     else         document.write( "No" );       return ; }   // Driver code var N = 4;   var adj = [];   for ( var i = 0; i <= N + 1; i++)     adj.push( new Array());   addEdge(adj, 1, 2); addEdge(adj, 2, 3); addEdge(adj, 3, 4);   DFS(adj, N); Â
Â
</script> |
Yes
Â
Time Complexity: O(N + E)
Auxiliary Space: Â O(N)Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!