We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Python 3, based on solution from @chuntao_liu_0118 in these comments. Splits up the logic a bit into a few functions with the intention to be slightly more readable. Also should work for arbitrarily many posts.
defhanoi_posts_to_int(nstacks,posts):ndisks=len(posts)base=2**ndisksres=0forj,postinenumerate(posts):res+=(2**j)*(base**(nstacks-post))returnresdefhanoi_neighbours(state,nstacks,ndisks):base=2**ndisksnums=[(state// (base**j)) % base for j in range(nstacks-1, -1, -1)]top_nums=[2**ndisksifnum==0else(num&~(num-1))fornuminnums]forj,tnjinenumerate(top_nums):fork,tnkinenumerate(top_nums):if(j==k)or(tnj>=tnk):continueneighbour=state-((tnj)*(base**((nstacks-1)-j)))+((tnj)*(base**((nstacks-1)-k)))yieldneighbourdefhanoi_general(nstacks,posts):ndisks=len(posts)source=hanoi_posts_to_int(nstacks,posts)base=2**ndiskstarget=((2**ndisks)-1)*(base**(nstacks-1))to_explore=[source]explored=set([source])parent={}whileto_explore:to_explore_next=[]forvinto_explore:forwinhanoi_neighbours(v,nstacks,ndisks):ifwinexplored:continueexplored.add(w)parent[w]=vifw==target:breakto_explore_next.append(w)to_explore=to_explore_nextcurr=targetmoves=0whilecurrinparent:moves+=1curr=parent[curr]returnmovesdefhanoi(posts):returnhanoi_general(4,posts)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Gena Playing Hanoi
You are viewing a single comment's thread. Return to all comments →
Python 3, based on solution from @chuntao_liu_0118 in these comments. Splits up the logic a bit into a few functions with the intention to be slightly more readable. Also should work for arbitrarily many posts.