文章同步发表于
新年倒腾塔(汉诺塔)
效果图
头文件代码
#pragma once #ifndef _C_CHAPTER_3_ #include <vector> #include <functional> /* * 汉诺塔[A(n) -> C]分解为 * 1.[A(n-1) -> B] * 2.[A(1) -> C] * 3.[B(n-1) -> C] * 步骤1又可看作是 * 下一个[A(n) -> C] * 此时A(n)=A(n-1),C=B * 步骤3也可看作是 * 下一个[A(n) -> C] * 此时A(n)=B(n-1),C=C * 移动次数=2^n - 1 */ void Hanoi(int iDish = 0x03); void Hanoi_Move(int iDish, std::vector<int>& vecA, std::vector<int>& vecB, std::vector<int>& vecC, int& iSteps, std::function<void(int)> Hanoi_Status_CB); void Hanoi_Move(std::vector<int>& vecSrc, std::vector<int>& vecDst, int& iSteps, std::function<void(int)> Hanoi_Status_CB); void Hanoi_Status(std::vector<int>& vecA, std::vector<int>& vecB, std::vector<int>& vecC, int iSteps); #endif // !_C_CHAPTER_3_
CPP文件实现代码
#include "Chapter3.h" #include <iostream> #include <iomanip> #include <string> /* * 汉诺塔[A(n) -> C]分解为 * 1.[A(n-1) -> B] * 2.[A(1) -> C] * 3.[B(n-1) -> C] * 步骤1又可看作是 * 下一个[A(n) -> C] * 此时A(n)=A(n-1),C=B * 步骤3也可看作是 * 下一个[A(n) -> C] * 此时A(n)=B(n-1),C=C * 移动次数=2^n - 1 */ void Hanoi(int iDish) { //初始化 std::vector<int> vecA; std::vector<int> vecB; std::vector<int> vecC; for (int i = iDish; i > 0x00; --i) { vecA.push_back(i); } //步数 int iSteps = 0x00; //状态 Hanoi_Status(vecA, vecB, vecC, iSteps); //移动 Hanoi_Move(iDish, vecA, vecB, vecC, iSteps, [&](int iStep) { Hanoi_Status(vecA, vecB, vecC, iSteps); }); } void Hanoi_Move(int iDish, std::vector<int>& vecA, std::vector<int>& vecB, std::vector<int>& vecC, int& iSteps, std::function<void(int)> Hanoi_Status_CB) { //最后一个 if (0x01 == iDish) { Hanoi_Move(vecA, vecC, iSteps, Hanoi_Status_CB); } else { Hanoi_Move(iDish - 0x01, vecA, vecC, vecB, iSteps, Hanoi_Status_CB); Hanoi_Move(vecA, vecC, iSteps, Hanoi_Status_CB); Hanoi_Move(iDish - 0x01, vecB, vecA, vecC, iSteps, Hanoi_Status_CB); } } void Hanoi_Move(std::vector<int>& vecSrc, std::vector<int>& vecDst, int& iSteps, std::function<void(int)> Hanoi_Status_CB) { //移动 int iSrc = vecSrc.back(); vecDst.push_back(iSrc); vecSrc.pop_back(); // ++iSteps; Hanoi_Status_CB(iSteps); } void Hanoi_Status(std::vector<int>& vecA, std::vector<int>& vecB, std::vector<int>& vecC, int iSteps) { std::cout << "Steps =" << std::setw(0x04) << ((0x00 < iSteps) ? std::to_string(iSteps) : "---" )<< std::endl; //倒序输出 size_t ullTotalSize = vecA.size() + vecB.size() + vecC.size(); for (size_t i = ullTotalSize; i > 0x00; --i) { std::cout << " " << std::setw(0x02) << ((i > vecA.size()) ? "|" : std::to_string(vecA[i - 0x01])) << " " << std::setw(0x02) << ((i > vecB.size()) ? "|" : std::to_string(vecB[i - 0x01])) << " " << std::setw(0x02) << ((i > vecC.size()) ? "|" : std::to_string(vecC[i - 0x01])) << std::endl; } std::cout << " " << "A" << " " << "B" << " " << "C" << std::endl; std::cout << std::endl; }
Main函数调用代码
int main() { //Chapter3 /**/ { Hanoi(3); } }