递归实现汉诺塔原理及核心代码

//递归解决汉诺塔问题

/*现在有三根相邻的柱子,标号为A,B,C,A柱子上从下到上按金字塔状

* 叠放着n个不同大小的圆盘,现在把所有盘子一个一个移动到柱子c上,

* 并且每次移动同一根柱子上都不能出现大盘子在小盘子上方,请问至少需要多少次移动?*/

import javax.swing.JOptionPane;

public class HanNuoTa1 {
	public static void main(String args[]) {
		final int n = Integer.parseInt(JOptionPane.showInputDialog("请输入盘子数:"));
		mov(n, "a", "b", "c");
		System.exit(0);
	}

	static void mov(int n, String a, String b, String c) {
		if (n == 1)
			System.out.println(n + ":" + a + "->" + c);
		else {
			mov(n - 1, a, c, b);
			System.out.println(n + ":" + a + "->" + c);

			mov(n - 1, b, a, c);
		}

	}

}

输出移动次数,并用mov函数移动

import javax.swing.JOptionPane;

public class HanNuoTa2 {
	static int s = 0;

	public static void main(String args[]) {
		int n = Integer.parseInt(JOptionPane.showInputDialog("请输入盘子个数:"));
		hn(n, 'a', 'b', 'c');
		System.out.println(s);
		System.exit(0);
	}

	static void hn(int n, char a, char b, char c) {
		if (n == 1) {
			move(a, c);
			s++;
		} else {
			hn(n - 1, a, c, b);
			move(a, c);
			hn(n - 1, b, a, c);
			s++;
		}
	}

	static void move(char x, char y) {

		System.out.println(x + "->" + y);
	}

}

由于笔者水平有限,先用简单的JApplet显示,稍后会做出Swing界面的汉诺塔

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class HanNuoTaGUI extends JApplet implements ActionListener {

	JLabel label;
	JTextField input;
	JTextArea outputArea;
	String output = "";
	JScrollPane scroller;
	int step = 0;

	public void init() {
		label = new JLabel("Enter number of disks ( 1-9 ): ");
		input = new JTextField(5);
		input.addActionListener(this);
		outputArea = new JTextArea(15, 20);
		scroller = new JScrollPane(outputArea);
		outputArea.setEditable(false);

		Container container = getContentPane();
		container.setLayout(new FlowLayout());
		setSize(318, 345);
		container.add(label);
		container.add(input);
		container.add(scroller);
		/*
		 * container.add(outputArea); JScrollPane本身是一个容器,放着JTextArea,
		 * 只需要在container中添加JScrollPane即可,不可以即把JTextArea添加在container和JScrollPane中
		 */

	}

	public void actionPerformed(ActionEvent e) {
		int n = Integer.parseInt(input.getText());
		if (n >= 9) {
			n = 9;
			showStatus("Invalid input.Value set to 9 by default!");
		}
		hn(n, 'a', 'b', 'c');
		outputArea.setText(output);

	}

	public void hn(int n, char c, char d, char e) {

		if (n == 1) {
			step++;
			output += "\n" + step + ": " + c + "-->" + e;
		} else {
			hn(n - 1, c, e, d);
			step++; // Be careful!!!
			output += "\n" + step + ": " + c + "-->" + e;

			hn(n - 1, d, c, e);
		}

	}
}

    原文作者: 汉诺塔问题
    原文地址: https://blog.csdn.net/codelife_long/article/details/22338289
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞