Queen's Attack II Discussions | Algorithms | HackerRank
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.
Solution is to iterate over obstacles and calculate their distances to the queen position if they are on the queen's path. Update the distances to keep the minimums and sum everything at the end
Python 3:
# Rather than checking if all possibles moves, iterate over# obstacles and check if they are on the queen path.# We find the minimum distances in each direction.# Calculate max distances in all directionsdir_w=r_q-1dir_e=n-r_qdir_n=c_q-1dir_s=n-c_qdir_nw=min(dir_n,dir_w)dir_sw=min(dir_s,dir_w)dir_ne=min(dir_n,dir_e)dir_se=min(dir_s,dir_e)# Find obstacles that are on queens way# and calculate the distancesforobsinobstacles:# Horizontalifobs[0]==r_q:ifobs[1]<c_q:# Wdist=c_q-obs[1]-1ifdist<dir_w:dir_w=distelse:# Edist=obs[1]-c_q-1ifdist<dir_e:dir_e=dist# Verticalelifobs[1]==c_q:ifobs[0]<r_q:# Ndist=r_q-obs[0]-1ifdist<dir_n:dir_n=distelse:# Edist=obs[0]-r_q-1ifdist<dir_s:dir_s=dist# Diagonalselifabs(obs[0]-r_q)==abs(obs[1]-c_q):# Decreasing diagonal: (1,1), (2,2), (3,3)# NW to SEifobs[0]-r_q==obs[1]-c_q:ifobs[0]<r_q:# NWdist=r_q-obs[0]-1ifdir_nw>dist:dir_nw=distelse:# SEdist=obs[0]-r_q-1ifdir_se>dist:dir_se=dist# Increasing diagonal: (1,3), (2,2), (3,1)elifobs[0]-r_q==-(obs[1]-c_q):ifobs[0]<r_q:# SWdist=r_q-obs[0]-1ifdir_sw>dist:dir_sw=distelse:# NEdist=obs[0]-r_q-1ifdir_ne>dist:dir_ne=dist
Queen's Attack II
You are viewing a single comment's thread. Return to all comments →
Solution is to iterate over obstacles and calculate their distances to the queen position if they are on the queen's path. Update the distances to keep the minimums and sum everything at the end
Python 3: