Minimum cost to traverse from one index to another in the String | C # implementation of the above approach . ; function to find the minimum cost ; graph ; adjacency matrix ; initialising adjacency matrix ; creating adjacency list ; pushing left adjacent elelemt for index ' k ' ; pushing right adjacent element for index ' k ' ; queue to perform BFS ; visited array ; variable to store depth of BFS ; BFS ; number of elements in the current level ; inner loop ; current element ; popping queue ; base case ; checking if the current node is required node ; iterating through the current node ; updating depth ; Driver Code ; input variables ; function to find the minimum cost
using System ; using System . Collections . Generic ; class GFG { static int findMinCost ( char [ ] s , int i , int j ) { List < int > [ ] gr = new List < int > [ 26 ] ; for ( int iN = 0 ; iN < 26 ; iN ++ ) gr [ iN ] = new List < int > ( ) ; bool [ , ] edge = new bool [ 26 , 26 ] ; for ( int k = 0 ; k < 26 ; k ++ ) for ( int l = 0 ; l < 26 ; l ++ ) edge [ k , l ] = false ; for ( int k = 0 ; k < s . Length ; k ++ ) { if ( k - 1 >= 0 && ! edge [ s [ k ] - 97 , s [ k - 1 ] - 97 ] ) { gr [ s [ k ] - 97 ] . Add ( s [ k - 1 ] - 97 ) ; edge [ s [ k ] - 97 , s [ k - 1 ] - 97 ] = true ; } if ( k + 1 <= s . Length - 1 && ! edge [ s [ k ] - 97 , s [ k + 1 ] - 97 ] ) { gr [ s [ k ] - 97 ] . Add ( s [ k + 1 ] - 97 ) ; edge [ s [ k ] - 97 , s [ k + 1 ] - 97 ] = true ; } } Queue < int > q = new Queue < int > ( ) ; q . Enqueue ( s [ i ] - 97 ) ; bool [ ] v = new bool [ 26 ] ; int d = 0 ; while ( q . Count > 0 ) { int cnt = q . Count ; while ( cnt -- > 0 ) { int curr = q . Peek ( ) ; q . Dequeue ( ) ; if ( v [ curr ] ) continue ; v [ curr ] = true ; if ( curr == s [ j ] - 97 ) return d ; foreach ( int it in gr [ curr ] ) q . Enqueue ( it ) ; } d ++ ; } return - 1 ; } public static void Main ( String [ ] args ) { String s = " abcde " ; int i = 0 ; int j = 4 ; Console . Write ( findMinCost ( s . ToCharArray ( ) , i , j ) ) ; } }