Minimum cost to traverse from one index to another in the String | Java 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
import java . util . * ; class GFG { static int findMinCost ( char [ ] s , int i , int j ) { Vector < Integer > [ ] gr = new Vector [ 26 ] ; for ( int iN = 0 ; iN < 26 ; iN ++ ) gr [ iN ] = new Vector < Integer > ( ) ; boolean [ ] [ ] edge = new boolean [ 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 < Integer > q = new LinkedList < Integer > ( ) ; q . add ( s [ i ] - 97 ) ; boolean [ ] v = new boolean [ 26 ] ; int d = 0 ; while ( q . size ( ) > 0 ) { int cnt = q . size ( ) ; while ( cnt -- > 0 ) { int curr = q . peek ( ) ; q . remove ( ) ; if ( v [ curr ] ) continue ; v [ curr ] = true ; if ( curr == s [ j ] - 97 ) return d ; for ( Integer it : gr [ curr ] ) q . add ( it ) ; } d ++ ; } return - 1 ; } public static void main ( String [ ] args ) { String s = " abcde " ; int i = 0 ; int j = 4 ; System . out . print ( findMinCost ( s . toCharArray ( ) , i , j ) ) ; } }