二漢諾塔問題を再帰的に総括する

1736 ワード

ハンノタは再帰入門のような誘導問題で、この過程を書いて、markは再帰します.他に役に立たない.
package hanoi;

public class Hanoi {
	/**
	 *  A      ,C     ,B     
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		int n = 4;
		hanio(n, 'A', 'C', 'B');
	}

	/**
	 *       :    n-1                            n-1                
	 * 
	 * @param n
	 * @param start
	 * @param destination
	 * @param temp
	 */
	public static void hanio(int n, char start, char destination, char temp) {
		if (n <= 0) {
			System.out.println("          0");
			return;
		}
		if (n == 1) {
			move(1, start, destination);
		} else {
			hanio(n - 1, start, temp, destination);
			move(n, start, destination);
			hanio(n - 1, temp, destination, start);
		}

	}

	/**
	 *          ,                               
	 * 
	 * @param current
	 * @param start
	 * @param destination
	 */
	public static void move(int current, char start, char destination) {
		StringBuilder sb = new StringBuilder();
		sb.append("move ").append(current);
		if (current == 1)
			sb.append("st dish from ");
		else if (current == 2)
			sb.append("nd dish from ");
		else if (current == 3)
			sb.append("rd dish from ");
		else
			sb.append("th dish from ");
		sb.append(start).append(" to ").append(destination);
		System.out.println(sb.toString());
	}
}

説明:たぶんこの様子でしょう.3と4を走っても大丈夫です.他を見ていないで、ほほほ.