Hanoi Tower(Towers of Hanoi)

帅比萌擦擦* 提交于 2019-11-29 11:57:09

This is the instruction by instruction of solving towers of Hanoi problem.

   move(1,X,Y,_) :-  
        write('Move top disk from '), 
        write(X), 
        write(' to '), 
        write(Y), 
        nl. 
    move(N,X,Y,Z) :- 
        N>1, 
        M is N-1, 
        move(M,X,Z,Y), 
        move(1,X,Y,_), 
        move(M,Z,Y,X).

Attack the problem in such a way: In the instruction by instruction solution we don't change the contents of X,Y or Z. But in your problem, you will eventually change the contents of them.

UPDATE: Since it is declared that this is not a homework question, here is the full answer:

towersOfHanoi(N,A,B,C,A4,B4,C4) :- move(N,A,B,C,A4,B4,C4),!.

move(1,[H|T],B,C,A1,B1,C1) :-  A1 = T,
                               B1 = [H|B],
                               C1 = C.
move(N,A,B,C,A4,B4,C4) :-   N>1, 
                            M is N-1, 
                            move(M,A,C,B,A1,C1,B1), 
                            move(1,A1,B1,C1,A2,B2,C2), 
                            move(M,C2,B2,A2,C4,B4,A4).
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!