Construct a graph using N vertices whose shortest distance between K pair of vertices is 2 | Javascript program to implement the above approach ; Function to construct the simple and connected graph such that the distance between exactly K pairs of vertices is 2 ; Stores maximum possible count of edges in a graph ; Base Case ; Stores edges of a graph ; Connect all vertices of pairs ( i , j ) ; Print first ( ( N - 1 ) + Max - K ) elements of edges [ ] ; Driver Code
class pair { constructor ( first , second ) { this [ 0 ] = first ; this [ 1 ] = second ; } } function constGraphWithCon ( N , K ) { var Max = ( ( N - 1 ) * ( N - 2 ) ) / 2 ; if ( K > Max ) { document . write ( - 1 + " " ) ; return ; } var ans = [ ] ; for ( var i = 1 ; i < N ; i ++ ) { for ( var j = i + 1 ; j <= N ; j ++ ) { ans . push ( [ i , j ] ) ; } } for ( var i = 0 ; i < ( N - 1 ) + Max - K ; i ++ ) { document . write ( ans [ i ] [ 0 ] + " " + ans [ i ] [ 1 ] + " " ) ; } } var N = 5 , K = 3 ; constGraphWithCon ( N , K ) ;