1- using System . Diagnostics ;
1+ using System . Collections . Generic ;
2+ using System . Diagnostics ;
23
34namespace Advanced . Algorithms . DynamicProgramming
45{
@@ -10,11 +11,7 @@ public class TowerOfHanoi
1011 {
1112 public static int Tower ( int numOfDisks )
1213 {
13- var minMoves = 0 ;
14-
15- Tower ( numOfDisks , "a" , "b" , "c" , ref minMoves ) ;
16-
17- return minMoves ;
14+ return Tower ( numOfDisks , "a" , "b" , "c" , new Dictionary < int , int > ( ) ) ;
1815 }
1916
2017 /// <summary>
@@ -25,29 +22,39 @@ public static int Tower(int numOfDisks)
2522 /// <param name="aux"></param>
2623 /// <param name="dest"></param>
2724 /// <param name="moveCount"></param>
28- private static void Tower ( int n , string source , string aux , string dest , ref int moveCount )
25+ private static int Tower ( int n , string source , string aux , string dest , Dictionary < int , int > cache )
2926 {
3027 Debug . WriteLine ( "Moving disc {0} from pole {1} to {2}" , n , source , dest ) ;
3128
32- moveCount ++ ;
29+ if ( n == 1 )
30+ {
31+ return 1 ;
32+ }
3333
34- if ( n > 1 )
34+ if ( cache . ContainsKey ( n ) )
3535 {
36- ////assume without last disc on top we would be moving a disc from source to dest
37- //Tower(n - 1, source, aux, dest, ref moveCount);
36+ return cache [ n ] ;
37+ }
3838
39- ////The last disc we just moved above to destination was in source
40- ////that disc was definitely moved from aux to source (if it was in destination we would be not here)
41- //Tower(n - 1, aux, dest, source, ref moveCount);
39+ ////assume without last disc on top we would be moving a disc from source to dest
40+ //Tower(n - 1, source, aux, dest, ref moveCount);
4241
43- //or alternatively
44- //assume without last disc on top we would be moving a disc from aux to dest
45- Tower ( n - 1 , aux , source , dest , ref moveCount ) ;
42+ ////The last disc we just moved above to destination was in source
43+ ////that disc was definitely moved from aux to source (if it was in destination we would be not here)
44+ //Tower(n - 1, aux, dest, source, ref moveCount);
45+
46+ //or alternatively
47+ //assume without last disc on top we would be moving a disc from aux to dest
48+ var result = Tower ( n - 1 , aux , source , dest , cache )
49+
50+ //The last disc we just moved above to destination was in aux
51+ //that disc was definitely moved from source to aux (if it was in destination we would be done by now)
52+ + Tower ( n - 1 , source , dest , aux , cache ) + 1 ;
53+
54+ cache . Add ( n , result ) ;
55+
56+ return result ;
4657
47- //The last disc we just moved above to destination was in aux
48- //that disc was definitely moved from source to aux (if it was in destination we would be done by now)
49- Tower ( n - 1 , source , dest , aux , ref moveCount ) ;
50- }
5158 }
5259
5360 }
0 commit comments