Advertisement
andyshon

Hanoi Tower

Oct 22nd, 2017
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. // Hanoi Tower.cpp
  2.  
  3. #include "stdafx.h"
  4. #include <stdio.h>
  5. #include <iostream>
  6. #include <time.h>
  7. using namespace std;
  8.  
  9. int iteration = 1;
  10. int top[3] = {0,0,0};   //указатель, (чтобы знать какому эл мы обращаемся)
  11. int const n = 3;    //количество дисков
  12. int const first_peg = 1;    //нумерация колышек
  13. int const end_peg = 3;
  14. int const mid_peg = 2;
  15. int stack[3][n];
  16.  
  17. void add(int qty, int word);
  18. void del(int qty);
  19. void Hanoi_Towers(int numb, int from, int to, int buf_peg);
  20.  
  21.  
  22. int main()
  23. {
  24.     setlocale(LC_ALL,"rus");
  25.     long int t = clock();
  26.     for (int i = n; i > 0; i--) {
  27.         add(0, i);
  28.         stack[1][i] = 0;
  29.         stack[2][i] = 0;
  30.     }
  31.     cout << "My_tower: " << endl;
  32.     for (int i = 0; i < n; i++) {
  33.         cout << stack[0][i] << "   " << stack[1][i] << "   " << stack[2][i] << "\n";
  34.     }
  35.     cout << "\n";
  36.     Hanoi_Towers(n, first_peg, end_peg, mid_peg);
  37.     cout << "The time of execute the program " << clock() - t << " ms. " <<endl;
  38.     system("pause");
  39.     return 0;
  40.     }
  41.  
  42. //добавляем элементы в стек
  43. void add(int qty, int word) {
  44.     if (top[qty] >= n) {
  45.         cout << "Full stack!!!!!!!!!" << endl;
  46.     }
  47.     else {
  48.         for (int i = top[qty] - 1; i >= 0; i--)
  49.             stack[qty][i + 1] = stack[qty][i];
  50.         stack[qty][0] = word;
  51.         top[qty]++;
  52.     }
  53. }
  54. //удаление элементов со стека
  55. void del(int qty) {
  56.     if (top[qty] <= 0) {
  57.         cout << "Empty stack!!!!!!!" << endl;
  58.     }
  59.     else {
  60.         for (int i = 0; i < (top[qty] - 1); i++)
  61.             stack[qty][i] = stack[qty][i + 1];
  62.         top[qty]--;
  63.         stack[qty][top[qty]] = 0;
  64.     }
  65. }
  66.  
  67. void Hanoi_Towers(int numb, int from, int to, int buf_peg)
  68. {
  69.     if (numb != 0)
  70.     {
  71.         Hanoi_Towers(numb - 1, from, buf_peg, to);
  72.  
  73.         cout << "Iteration " << iteration << ": " << from << " --> " << to << endl;
  74.         iteration++;
  75.  
  76.         add(to - 1, stack[from - 1][0]);
  77.         del(from - 1);
  78.  
  79.         for (int i = 0; i < n; i++) cout << stack[0][i] << "   " << stack[1][i] << "   " << stack[2][i] << "\n";
  80.         cout << "\n";
  81.  
  82.  
  83.         Hanoi_Towers(numb - 1, buf_peg, to, from);
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement