Hanoi Tower(Towers of Hanoi)

后端 未结 1 1398
长情又很酷
长情又很酷 2020-12-20 02:27

I\'m trying to do the Towers of Hanoi problem, what I have tried so far:

move(1,[H|T],B,C,A1,B1,C) :-  
  A1 = T,
  B1 = [H|B].
move(N,A,B,C,A1,B1,C) :- 
N&         


        
相关标签:
1条回答
  • 2020-12-20 02:49

    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).
    
    0 讨论(0)
提交回复
热议问题