Cost Based Tower of Hanoi | Javascript implementation of the approach ; Function to initialize the dp table ; Initialize with maximum value ; Function to return the minimum cost ; Base case ; If problem is already solved , return the pre - calculated answer ; Number of the auxiliary disk ; Initialize the minimum cost as Infinity ; Calculationg the cost for first case ; Calculating the cost for second case ; Minimum of both the above cases ; Store it in the dp table ; Return the minimum cost ; Driver code
let RODS = 3 ; let N = 3 ; let dp = new Array ( N + 1 ) ; function initialize ( ) { for ( let i = 0 ; i <= N ; i += 1 ) { dp [ i ] = new Array ( RODS + 1 ) ; for ( let j = 1 ; j <= RODS ; j ++ ) { dp [ i ] [ j ] = new Array ( RODS + 1 ) ; for ( let k = 1 ; k <= RODS ; k += 1 ) { dp [ i ] [ j ] [ k ] = Number . MAX_VALUE ; } } } } function mincost ( idx , src , dest , costs ) { if ( idx > N ) return 0 ; if ( dp [ idx ] [ src ] [ dest ] != Number . MAX_VALUE ) return dp [ idx ] [ src ] [ dest ] ; let rem = 6 - ( src + dest ) ; let ans = Number . MAX_VALUE ; let case1 = costs [ src - 1 ] [ dest - 1 ] + mincost ( idx + 1 , src , rem , costs ) + mincost ( idx + 1 , rem , dest , costs ) ; let case2 = costs [ src - 1 ] [ rem - 1 ] + mincost ( idx + 1 , src , dest , costs ) + mincost ( idx + 1 , dest , src , costs ) + costs [ rem - 1 ] [ dest - 1 ] + mincost ( idx + 1 , src , dest , costs ) ; ans = Math . min ( case1 , case2 ) ; dp [ idx ] [ src ] [ dest ] = ans ; return ans ; } let costs = [ [ 0 , 1 , 2 ] , [ 2 , 0 , 1 ] , [ 3 , 2 , 0 ] ] ; initialize ( ) ; document . write ( mincost ( 1 , 1 , 3 , costs ) ) ;