Minimum number of reversals to reach node 0 from every other node | C # program for the above approach ; 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 ; Enqueue adjacent nodes in the reversed graph to the queue , if not visited ; Enqueue 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
using System ; using System . Collections ; using System . Collections . Generic ; class GFG { static int minRev ( ArrayList edges , int n ) { Dictionary < int , ArrayList > graph = new Dictionary < int , ArrayList > ( ) ; Dictionary < int , ArrayList > graph_rev = new Dictionary < int , ArrayList > ( ) ; for ( int i = 0 ; i < edges . Count ; i ++ ) { int x = ( int ) ( ( ArrayList ) edges [ i ] ) [ 0 ] ; int y = ( int ) ( ( ArrayList ) edges [ i ] ) [ 1 ] ; if ( ! graph . ContainsKey ( x ) ) { graph [ x ] = new ArrayList ( ) ; } graph [ x ] . Add ( y ) ; if ( ! graph_rev . ContainsKey ( y ) ) { graph_rev [ y ] = new ArrayList ( ) ; } graph_rev [ y ] . Add ( x ) ; } Queue q = new Queue ( ) ; ArrayList visited = new ArrayList ( ) ; for ( int i = 0 ; i < n + 1 ; i ++ ) { visited . Add ( false ) ; } q . Enqueue ( 0 ) ; int ans = 0 ; while ( q . Count != 0 ) { int curr = ( int ) q . Peek ( ) ; visited [ curr ] = true ; int count = 0 ; q . Dequeue ( ) ; if ( graph_rev . ContainsKey ( curr ) ) { for ( int i = 0 ; i < graph_rev [ curr ] . Count ; i ++ ) { if ( ! ( bool ) visited [ ( int ) ( ( ArrayList ) graph_rev [ curr ] ) [ i ] ] ) { q . Enqueue ( ( int ) ( ( ArrayList ) graph_rev [ curr ] ) [ i ] ) ; } } } if ( graph . ContainsKey ( curr ) ) { for ( int i = 0 ; i < ( ( ArrayList ) graph [ curr ] ) . Count ; i ++ ) { if ( ! ( bool ) visited [ ( int ) ( ( ArrayList ) graph [ curr ] ) [ i ] ] ) { q . Enqueue ( ( int ) ( ( ArrayList ) graph [ curr ] ) [ i ] ) ; count ++ ; } } } ans += count ; } return ans ; } public static void Main ( string [ ] args ) { ArrayList edges = new ArrayList ( ) { new ArrayList ( ) { 0 , 1 } , new ArrayList ( ) { 1 , 3 } , new ArrayList ( ) { 2 , 3 } , new ArrayList ( ) { 4 , 0 } , new ArrayList ( ) { 4 , 5 } } ; int n = 6 ; Console . Write ( minRev ( edges , n ) ) ; } }