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.
fromsysimportstdinfromfunctoolsimportreducefromqueueimportdequedefget_states(state:int,n:int):"""returns a list of states that can be achieved from the given state"""top_disks=[]positions=set()forsizeinrange(n):pos=(state>>2*size)&3ifposnotinpositions:top_disks.append((size,pos))positions.add(pos)top_disks.sort()allowed_positions=set(range(4))states=[]forsize,posintop_disks:allowed_positions.discard(pos)forpos_inallowed_positions:new_state=(pos_<<2*size)|(state^(pos<<2*size))states.append(new_state)returnstatesdefhanoi(init_state:int,n:int):"""representeachpossiblearrangementasabinarynumberoflength2*n,wherenisthenumberofdisks.therightmost2digitsrepresentthepositionofdisk1,thenexttwodigitsrepresentthepositionofdisk2,etc.,thendoabfsofthegraphstartingatinit_state..."""queue=deque([(init_state,0)])visited={init_state}whilequeue:state,num_moves=queue.popleft()ifstate==0:returnnum_moveselse:states=get_states(state,n)forstateinstates:ifnotstateinvisited:queue.append((state,num_moves+1))visited.add(state)defmain():n=int(stdin.readline().strip())disks=map(int,stdin.readline().strip().split())state=reduce(lambdax,y:x|y,((pos-1)<<2*sizeforsize,posinenumerate(disks)))print(hanoi(state,n))if__name__=="__main__":main()
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 →
Most straightforward solution, in my opinion: