zoukankan      html  css  js  c++  java
  • 睡不着,随便写了下汉诺塔的解决方法。

    using System;
    using System.Collections.Generic;
    using System.Text;

    namespace ConsoleApplication1
    {
        
    class Program
        
    {
            
    static void Main(string[] args)
            
    {

                    
    int times = new HanoiTower(3).SolveTower();
                
                Console.WriteLine(
    "一共需要{0}次", times);

                Console.ReadKey();
            }

        }


        
    class HanoiTower
        
    {
            
    private int plates;
            
    public HanoiTower(int plates)
            
    {
                
    this.plates = plates;
            }

            
    public int SolveTower()
            
    {
                
    return SolveTower(plates, "A""B""C");
            }

            
    private int SolveTower(int plates,string a, string b, string c)
            
    {
                
    int count = 0;
                
    if (plates <= 0)
                    
    throw new ArgumentOutOfRangeException("plates","盘子数必须是大于0的整数");
                
    if (plates == 1)
                

                    move(a, c);
                    
    return 1;
                }

                count 
    += SolveTower(plates - 1, a, c, b);
                count 
    += SolveTower(1, a, b, c);
                count 
    += SolveTower(plates - 1, b, a, c);
                
    return count;

            }

            
    private void move(string a, string c)
            
    {
                Console.WriteLine(a 
    + " => " + c);
            }

        }

    }

    张旋(zxsoft)
    如对本文有什么疑问,请在下面写下留言,谢谢!

  • 相关阅读:
    高并发系统设计(二十):分布式架构如何跟踪排查慢请求问题?
    Git将多个commit合并成一个commit
    高并发系统设计(十九)【注册中心】:微服务架构结合RPC框架如何做到分布式系统寻址?
    高并发系统设计(十八):【RPC框架】10万QPS下如何实现毫秒级的服务调用?
    AfxSocketInit()
    TEXTMETRIC 结构详解
    OnInitialUpdate函数
    SetForegroundWindow
    GetSafeHwnd()函数
    MFC之CCommandLineInfo
  • 原文地址:https://www.cnblogs.com/zxsoft/p/1210400.html
Copyright © 2011-2022 走看看