Kth largest node among all directly connected nodes to the given node in an undirected graph | Function to print Kth node for each node ; Vector to store nodes directly connected to ith node along with their values ; Add edges to the vector along with the values of the node ; Sort neighbors of every node and find the Kth node ; Get the kth node ; If total nodes are < k ; Driver code
def findKthNode ( u , v , n , val , V , k ) : NEW_LINE INDENT g = [ [ ] for i in range ( V ) ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT g [ u [ i ] ] . append ( ( val [ v [ i ] ] , v [ i ] ) ) NEW_LINE g [ v [ i ] ] . append ( ( val [ u [ i ] ] , u [ i ] ) ) NEW_LINE DEDENT for i in range ( 0 , V ) : NEW_LINE INDENT if len ( g [ i ] ) > 0 : NEW_LINE INDENT g [ i ] . sort ( ) NEW_LINE DEDENT if k <= len ( g [ i ] ) : NEW_LINE INDENT print ( g [ i ] [ - k ] [ 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT V = 3 NEW_LINE val = [ 2 , 4 , 3 ] NEW_LINE u = [ 0 , 0 , 1 ] NEW_LINE v = [ 2 , 1 , 2 ] NEW_LINE n , k = len ( u ) , 2 NEW_LINE findKthNode ( u , v , n , val , V , k ) NEW_LINE DEDENT