function hanoi(n,time) if nargin<2 time=1; %set time if nargin<1 n=10; end end global dt dt=time; A=ones(1,n); step=0; draw(A,step,0); title(['step:' num2str(step)]) pause trans4(n,1,4,A,step); function [A,step]=trans4(n,i,j,A,step) global dt if n==0 return elseif n==1 step=step+1; A(step+1,:)=A(step,:); A(step+1,1)=j; draw(A,step,1) title(['step:' num2str(step)]) pause(dt) return end s=floor((sqrt(2*n))); if n>s*(s+1)/2 s=s+1; end tmp=1:4; k=find(tmp~=i & tmp~=j); [A,step]=trans4(n-s,i,k(1),A,step); [A,step]=trans3(n+1-s:n,i,j,k(2),A,step); [A,step]=trans4(n-s,k(1),j,A,step); n=n-s; % pause function [A,step]=trans3(a,i,j,k,A,step) global dt l=length(a); if l~=1 [A,step]=trans3(a(1:l-1),i,k,j,A,step); [A,step]=trans3(a(l),i,j,k,A,step); [A,step]=trans3(a(1:l-1),k,j,i,A,step); else step=step+1; A(step+1,:)=A(step,:); A(step+1,a)=j; draw(A,step,a) title(['step:' num2str(step)]) pause(dt) end function draw(A,step,index) clf hold on dh=0.02; rmin=0.1; n=size(A,2); dr=(0.5-rmin)/n; for i=1:4 h=dh; ind=find(A(step+1,:)==i); for j=ind(end:-1:1) if j==index plot([i-rmin-(j-1)*dr,i+rmin+(j-1)*dr],[h h],'r-','linewidth',3.8) continue end plot([i-rmin-(j-1)*dr,i+rmin+(j-1)*dr],[h h],'linewidth',3.8) h=h+dh; end plot([i i],[0 dh*n*8/5],'k-','linewidth',3) end axis([0 5 0 ceil(dh*n)])