fork download
  1. #include <vector>
  2. #include <cstdio>
  3.  
  4. using namespace std;
  5.  
  6. #define _countof(array) (sizeof(array) / sizeof(array[0]))
  7. typedef unsigned char uchar;
  8. typedef struct {
  9. uchar src, dst, work, discs;
  10. } hanoi;
  11. vector<uchar> pegs[3];
  12.  
  13. int hanoi_init(hanoi h)
  14. {
  15. if(h.src > 2) return 1;
  16. if(h.dst > 2) return 2;
  17. if(h.work > 2) return 3;
  18. if(h.discs > 15) return 4;
  19. if(h.src == h.dst || h.dst == h.work || h.work == h.src) return 5;
  20. for(int i = (int)h.discs; i > 0; --i) pegs[h.src].push_back(i);
  21. return 0;
  22. }
  23.  
  24. int hanoi_stat()
  25. {
  26. fprintf(stdout, "Pegs\n");
  27. for(int j = 0; j < _countof(pegs); ++j){
  28. fprintf(stdout, " [%d]:", j);
  29. for(vector<uchar>::iterator it=pegs[j].begin(); it != pegs[j].end(); ++it)
  30. fprintf(stdout, " %d", (int)*it);
  31. fprintf(stdout, "\n");
  32. }
  33. return 0;
  34. }
  35.  
  36. int hanoi_move(hanoi m)
  37. {
  38. pegs[m.dst].push_back(pegs[m.src].back());
  39. pegs[m.src].pop_back();
  40. hanoi_stat();
  41. return 0;
  42. }
  43.  
  44. hanoi hanoi_next(hanoi h)
  45. {
  46. if(!h.discs) return h;
  47. hanoi m = hanoi_next(hanoi{h.src, h.work, h.dst, (uchar)(h.discs - 1)});
  48. if(m.discs) hanoi_move(m);
  49. hanoi_move(h);
  50. m = hanoi_next(hanoi{h.work, h.dst, h.src, (uchar)(h.discs - 1)});
  51. if(m.discs) hanoi_move(m);
  52. return hanoi{0, 0, 0, 0}; // discs = 0 for stop recursion
  53. }
  54.  
  55. int main(int ac, char **av)
  56. {
  57. hanoi h = {0, 1, 2, 4};
  58. int r = hanoi_init(h);
  59. if(r){
  60. fprintf(stderr, "illeagal parameter: error %d\n", r);
  61. }else{
  62. hanoi_stat();
  63. hanoi_next(h);
  64. }
  65. return 0;
  66. }
Success #stdin #stdout 0.01s 5516KB
stdin
Standard input is empty
stdout
Pegs
 [0]: 4 3 2 1
 [1]:
 [2]:
Pegs
 [0]: 4 3 2
 [1]:
 [2]: 1
Pegs
 [0]: 4 3
 [1]: 2
 [2]: 1
Pegs
 [0]: 4 3
 [1]: 2 1
 [2]:
Pegs
 [0]: 4
 [1]: 2 1
 [2]: 3
Pegs
 [0]: 4 1
 [1]: 2
 [2]: 3
Pegs
 [0]: 4 1
 [1]:
 [2]: 3 2
Pegs
 [0]: 4
 [1]:
 [2]: 3 2 1
Pegs
 [0]:
 [1]: 4
 [2]: 3 2 1
Pegs
 [0]:
 [1]: 4 1
 [2]: 3 2
Pegs
 [0]: 2
 [1]: 4 1
 [2]: 3
Pegs
 [0]: 2 1
 [1]: 4
 [2]: 3
Pegs
 [0]: 2 1
 [1]: 4 3
 [2]:
Pegs
 [0]: 2
 [1]: 4 3
 [2]: 1
Pegs
 [0]:
 [1]: 4 3 2
 [2]: 1
Pegs
 [0]:
 [1]: 4 3 2 1
 [2]: