提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
河内塔的递归方法。
public class Main { /** 来自 nowjava.com - 时 代 Java**/ // recursively move disks between towers public static void solveTowers(int disks, int sourcePeg, int destinationPeg, int tempPeg) { // base case -- only one disk to move if (disks == 1) { System.out.printf("%n%d --> %d", sourcePeg, destinationPeg); return; } // recursion step -- move (disk - 1) disks from sourcePeg // to tempPeg using destinationPeg solveTowers(disks - 1, sourcePeg, tempPeg, destinationPeg);/** 来 自 nowjava - 时代Java**/ // move last disk from sourcePeg to destinationPeg System.out.printf("%n%d --> %d", sourcePeg, destinationPeg); // move (disks - 1) disks from tempPeg to destinationPeg solveTowers(disks - 1, tempPeg, destinationPeg, sourcePeg); } public static void main(String[] args) { int startPeg = 1; // value 1 used to indicate startPeg in output int endPeg = 3;