Tower of Hanoi
Description
Tower of Hanoi is a well-known problem.There are n plates of different sizes (radius 1-n) stacked on three pillars A, B and C.They are all stacked on A at first, your goal is moving all the plates from A to C in minimum legal steps.
The rules of moving are as follows:
1、You are allowed to move one plate once (from top of one pillar to top of another pillar)
2、Ensure that the smaller plates are on the top of the bigger one,and there is nothing under the biggest plate.
public class Solution {
/**
* @param n: the number of disks
* @return: the order of moves
*/
public List<String> towerOfHanoi(int n) {
// write your code here
List<String> results = new ArrayList<>() ;
char A = 'A', B = 'B', C = 'C' ;
helper(n , results , A , B , C) ;
return results ;
}
public void helper(int n , List<String> results , char A ,char B ,char C ){
if(n == 1){
results.add("from " + A + " to " + C) ;
}else{
helper(n-1 , results , A ,C,B);
helper(1 , results , A ,B,C);
helper(n-1 , results , B ,A,C);
}
}
}
本文详细介绍了经典的汉诺塔问题及其解决方法。通过递归算法实现盘子从A柱移动到C柱的过程,并确保在移动过程中始终遵循小盘在大盘之上的规则。文章提供了完整的Java代码实现。
4283

被折叠的 条评论
为什么被折叠?



