汉若塔游戏非递归解法(c#)

本文介绍了一种使用C#实现的汉诺塔问题非递归解决方案。该方案通过栈来跟踪移动步骤,避免了传统递归方法的堆栈溢出风险,适用于任意数量的盘子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

汉若塔游戏非递归解法(c#实现)

// 汉若塔游戏非递归解法(c#) 
using System;
using System.Collections.Generic;
using System.Text;

namespace hanruota
{
    
class Program
    {
        
static void Main(string[] args)
        {
            Console.WriteLine(
"请输入盘子数:");
            
int diskCount =int.Parse( Console.ReadLine());
            HanRuoTa a 
= new HanRuoTa(diskCount);            
            a.Run();
            Console.ReadLine();
        }
    }
    
class HanRuoTa
    {
        Stack
<Step> StepList = new Stack<Step>();
        Step S;
        
public struct Step
        {
            
public int N; //盘子个数  
            public int x, y, z;//位置   
        }
        
public HanRuoTa(int n)
        {
            S 
= new Step();
            S.N 
= n;
            S.x 
= 1;
            S.y 
= 2;
            S.z 
= 3;
        }

        
public void Run()
        {    
            
//初始化问题  
            Step S1 = S;
            StepList.Push(S1);
            
while(true)
            {
                
//栈为空,代表问题已解决      
                if (StepList.Count == 0)
                {
                    
break;
                }
                
else
                {    
                    
int t=0;        
                    S 
= StepList.Pop();                     
                    
if (S.N <= 1)
                    {
                        Move(S.x, S.z);
                    }
                    
else//分解为子问题压入栈(倒序)
                    {
                        
//第三步
                        S1 = new Step();
                        S1 
= S;
                        S1.N
--;
                        Swap(
ref S1.x, ref S1.y);
                        StepList.Push(S1);
                        
//第二步
                        S1 = new Step();
                        S1 
= S;
                        S1.N 
= 1;
                        StepList.Push(S1);
                        
//第一步
                        S1 = new Step();
                        S1 
= S;
                        S1.N
--;
                        Swap(
ref S1.y, ref S1.z);
                        StepList.Push(S1);
                    }
                }
            }
        }
        
void Swap(ref int a, ref int b)
        {
            
int t= a;
            a 
= b;
            b 
= t; 
        }
        
void  Move(int f, int t)
        {
            Console.WriteLine(f.ToString() 
+ "->" + t.ToString());
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值