用栈来求解汉诺塔问题(offer收割)

问题

  汉诺塔问题比较经典,这里修改一下游戏规则:现在限制不能从最左侧的塔直接移动到最右侧,也不能从最右侧直接移动到最左侧,而是必须经过中间。求当塔有N层的时候,打印最优移动过程和最优移动总步数。

代码

代码1:经典递归算法

package com.iqiyi;

public class Code1_6_1 {
	
	public static void main(String[] args){
		int count=hanoi(5, "left", "right");
		System.out.println(String.format("It will move %d steps.", count));
	}
	
	public static void move(int index,String from,String to){
		System.out.println(String.format("Move %d from %s to %s", index, from, to));
	}
	
	public static int hanoi(int n,String from,String to){
		if(n==1){
			move(1, from, "mid");
			move(1,"mid",to);
			return 2;
		}
		int count1=hanoi(n-1, from, to);
		move(n, from, "mid");
		int count2=hanoi(n-1, to, from);
		move(n, "mide", to);
		int count3=hanoi(n-1, from, to);
		return count1+count2+count3+2;
	}
}
复制代码

代码2:利用栈的非递归算法

package com.iqiyi;

import java.util.Stack;

public class Code1_6_2 {
	public static int hanoi(int n){
		Stack<Integer> stack1=new Stack<Integer>();
		Stack<Integer> stack2=new Stack<Integer>();
		Stack<Integer> stack3=new Stack<Integer>();
		stack1.push(Integer.MAX_VALUE);
		stack2.push(Integer.MAX_VALUE);
		stack3.push(Integer.MAX_VALUE);
		int t=n;
		while(t>0){
			stack1.push(t);
			t--;
		}
		int count=0;
		int action=1;
		int first=stack1.pop();
		stack2.push(first);
		move(first, action);
		count++;
		while(stack3.size()!=(n+1)){
			if(action==1 || action==2){
				if(stack2.peek()>stack3.peek()){
					first=stack3.pop();
					stack2.push(first);
					action=3;
				}
				else{
					first=stack2.pop();
					stack3.push(first);
					action=4;
				}
			}
			else {
				if(stack1.peek()>stack2.peek()){
					first=stack2.pop();
					stack1.push(first);
					action=2;
				}
				else{
					first=stack1.pop();
					stack2.push(first);
					action=1;
				}
			}
			move(first, action);
			count++;
		}
		return count;
		
	}
	
	public static void move(int index,int action){
		switch (action) {
		case 1:
			System.out.println(String.format("Move %d from 1 to 2", index));
			break;
		case 2:
			System.out.println(String.format("Move %d from 2 to 1", index));
			break;
		case 3:
			System.out.println(String.format("Move %d from 3 to 2", index));
			break;
		case 4:
			System.out.println(String.format("Move %d from 2 to 3", index));
			break;
		default:
			break;
		}
	}
	
	public static void main(String[] args){
		int count=hanoi(5);
		System.out.println(String.format("It will move %d steps.", count));
	}

}
复制代码

转载于:https://juejin.im/post/5c3bf3a3e51d455230711ab3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值