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.
classNode:def__init__(self,x,y):self.state=(x,y)self.parent:Node=Noneself.action:strdeffind_path(node):path=[]whilenode.parentisnotNone:path.append(node.action)node=node.parentreturnpath[::-1]#Reversethepathtogetthecorrectorderdefactions(current_node,n):current_r,current_c=current_node.statechildren=[]# a = [UL, UR, R, LR, LL, L]dr=[-2,-2,0,2,2,0]dc=[-1,1,2,1,-1,-2]foriinrange(0,6):possible_r=current_r+dr[i]possible_c=current_c+dc[i]# Check it is not out of bounds.ifpossible_r<0orpossible_c<0:continueifpossible_r>n-1orpossible_c>n-1:continuechild=Node(possible_r,possible_c)child.parent=current_nodeifi==0:child.action="UL"elifi==1:child.action="UR"elifi==2:child.action="R"elifi==3:child.action="LR"elifi==4:child.action="LL"elifi==5:child.action="L"children.append(child)returnchildrendefprintShortestPath(n,i_start,j_start,i_end,j_end):# start_node = Node(i_start, j_start)start_node=Node(i_start,j_start)goal_node=Node(i_end,j_end)visited=set()queue=[start_node]whilequeue:current_node=queue.pop(0)ifcurrent_node.state==goal_node.state:path=find_path(current_node)print(len(path))print(' '.join(path))returnifcurrent_node.statenotinvisited:visited.add(current_node.state)children=actions(current_node,n)forchildinchildren:ifchild.statenotinvisitedandchildnotinqueue:visited.add(child.state)#Nodesareaddedtothevisitedsetassoonastheyareaddedtothequeue,# ensuring they are not re-added.queue.append(child)print("Impossible")
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Red Knight's Shortest Path
You are viewing a single comment's thread. Return to all comments →
Easily readible python solution