Minimum number of reversals to reach node 0 from every other node | Function to find minimum reversals ; Add all adjacent nodes to the node in the graph ; Insert edges in the graph ; Insert edges in the reversed graph ; Create array visited to mark all the visited nodes ; Stores the number of edges to be reversed ; BFS Traversal ; Pop the current node from the queue ; mark the current node visited ; Intitialize count of edges need to be reversed to 0 ; Push adjacent nodes in the reversed graph to the queue , if not visited ; Push adjacent nodes in graph to the queue , if not visited count the number of nodes added to the queue ; Update the reverse edge to the final count ; Return the result ; Driver Code ; Given edges to the graph ; Number of nodes ; Function Call
def minRev ( edges , n ) : NEW_LINE INDENT graph = dict ( ) NEW_LINE graph_rev = dict ( ) NEW_LINE for i in range ( len ( edges ) ) : NEW_LINE INDENT x = edges [ i ] [ 0 ] ; NEW_LINE y = edges [ i ] [ 1 ] ; NEW_LINE if x not in graph : NEW_LINE INDENT graph [ x ] = [ ] NEW_LINE DEDENT graph [ x ] . append ( y ) ; NEW_LINE if y not in graph_rev : NEW_LINE INDENT graph_rev [ y ] = [ ] NEW_LINE DEDENT graph_rev [ y ] . append ( x ) ; NEW_LINE DEDENT q = [ ] NEW_LINE visited = [ 0 for i in range ( n ) ] NEW_LINE q . append ( 0 ) ; NEW_LINE ans = 0 ; NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT curr = q [ 0 ] NEW_LINE visited [ curr ] = 1 ; NEW_LINE count = 0 ; NEW_LINE q . pop ( 0 ) ; NEW_LINE if curr in graph_rev : NEW_LINE INDENT for i in range ( len ( graph_rev [ curr ] ) ) : NEW_LINE INDENT if ( not visited [ graph_rev [ curr ] [ i ] ] ) : NEW_LINE INDENT q . append ( graph_rev [ curr ] [ i ] ) ; NEW_LINE DEDENT DEDENT DEDENT if curr in graph : NEW_LINE INDENT for i in range ( len ( graph [ curr ] ) ) : NEW_LINE INDENT if ( not visited [ graph [ curr ] [ i ] ] ) : NEW_LINE INDENT q . append ( graph [ curr ] [ i ] ) ; NEW_LINE count += 1 NEW_LINE DEDENT DEDENT DEDENT ans += count ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT edges = [ ] NEW_LINE edges = [ [ 0 , 1 ] , [ 1 , 3 ] , [ 2 , 3 ] , [ 4 , 0 ] , [ 4 , 5 ] ] ; NEW_LINE n = 6 ; NEW_LINE print ( minRev ( edges , n ) ) NEW_LINE DEDENT