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.
defsteps_mhanoy(tower):l=len(tower)rangel=range(l)# it'll help optimisation, the solution# fails time to timesteps=0state=0# state is binary of |discN|discN-1|...|disc2|disc1|# where each discK = rod on which that disc is locatedwin=0# win is state where each discK == 00bdefmove(rod,disc):nonlocalstatedisc*=2# each disc is represented as 2 bitsstate&=~(3<<disc)# 3 = all rods -> remove all rods for that discstate|=rod<<disc# write down roddefget_rod_top(rod):st=stateforiinrangel:r=3&st# get topmost disc rodifr==rod:returnist>>=2# move to the next discreturnl# we can return anything, but l is better because we get# less comparison laterforiinrangel:# fill in the statemove(tower[i]-1,i)ifstate==win:# bfs won't work if we are already in a right statereturn0# to solve the case, we will use breadth-first searchbfs=deque()# the list of unexplored statesbfs.append(state)# root state atopdepth=dict()# depth measuredepth[state]=0# depth of starting state is 0range4=range(4)# just a bit of optimisation will helpwhileTrue:cstate=state=bfs.popleft()# get the next unexplored statesteps=depth[state]# get it's depth# get all the tops of the rods to move themd=[get_rod_top(r)forrinrange4]forfroinrange4:# try to move from every rodifd[fro]==l:# if rod is empty, skipcontinuefortoinrange4:# iterate over every other rod to put ontoifd[to]>d[fro]:# if the disc is bigger on the rod or rod is emptystate=cstate# restore state to state of explorationmove(to,d[fro])# move the rodifstate==win:# if achieved finish state, return immediatelyreturnsteps+1# if state hadn't been found yetifstatenotindepth:# set state depthdepth[state]=steps+1# add into exploration queuebfs.append(state)returndepth[0]
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 →
My solution: