Minimum cost to traverse from one index to another in the String | 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 ; input variables ; function to find the minimum cost
function findMinCost ( s , i , j ) { var gr = Array . from ( Array ( 26 ) , ( ) => new Array ( ) ) ; var edge = Array . from ( Array ( 26 ) , ( ) => Array ( 26 ) ) ; for ( var k = 0 ; k < 26 ; k ++ ) for ( var l = 0 ; l < 26 ; l ++ ) edge [ k ] [ l ] = 0 ; for ( var k = 0 ; k < s . length ; k ++ ) { if ( k - 1 >= 0 && ! edge [ s [ k ] . charCodeAt ( 0 ) - 97 ] [ s [ k - 1 ] . charCodeAt ( 0 ) - 97 ] ) gr [ s [ k ] . charCodeAt ( 0 ) - 97 ] . push ( s [ k - 1 ] . charCodeAt ( 0 ) - 97 ) , edge [ s [ k ] . charCodeAt ( 0 ) - 97 ] [ s [ k - 1 ] . charCodeAt ( 0 ) - 97 ] = 1 ; if ( k + 1 <= s . length - 1 && ! edge [ s [ k ] . charCodeAt ( 0 ) - 97 ] [ s [ k + 1 ] . charCodeAt ( 0 ) - 97 ] ) gr [ s [ k ] . charCodeAt ( 0 ) - 97 ] . push ( s [ k + 1 ] . charCodeAt ( 0 ) - 97 ) , edge [ s [ k ] . charCodeAt ( 0 ) - 97 ] [ s [ k + 1 ] . charCodeAt ( 0 ) - 97 ] = 1 ; } var q = [ ] ; q . push ( s [ i ] . charCodeAt ( 0 ) - 97 ) ; var v = Array ( 26 ) . fill ( 0 ) ; var d = 0 ; while ( q . length > 0 ) { var cnt = q . length ; while ( cnt -- > 0 ) { var curr = q [ 0 ] ; q . shift ( ) ; if ( v [ curr ] ) continue ; v [ curr ] = 1 ; if ( curr == s [ j ] . charCodeAt ( 0 ) - 97 ) return d ; for ( var it = 0 ; it < gr [ curr ] . length ; it ++ ) { q . push ( gr [ curr ] [ it ] ) ; } } d ++ ; } return - 1 ; } var s = " " ; var i = 0 ; var j = 4 ; document . write ( findMinCost ( s , i , j ) ) ;