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.
Main Points -
1. Min path for knightL(a,b) will be same as knight(b, a). This observation reduces half of the processing
2. Think matrix as tree with root node at 0,0 and all possible next cell which can be taken from curr node as child.
The BFS traversal will give the shorted path len.
fromcollectionsimportdequeclassSolution:defknightlOnAChessboard(self,n):res=[[-1for_inrange(n-1)]for_inrange(n-1)]foriinrange(1,n):forjinrange(1,n):# there will be two paris for which the path len will be same, a,b and b,a.# So to optimize just reuse if other pair is already computed. This reduces the computation to halfres[i-1][j-1]=res[j-1][i-1]ifres[j-1][i-1]!=-1elseself.knight_min_move(n,i,j)returnresdefknight_min_move(self,n,a,b):# Using a set to have distinct values onlychoices={(a,b),(a,-b),(-a,b),(-a,-b),(b,a),(b,-a),(-b,a),(-b,-a)}visited=[[-1for_inrange(n)]for_inrange(n)]visited[0][0]=0q=deque()q.append((0,0,0))#Storesrow_index,col_index,depthwhilelen(q)!=0:nodes_at_level=len(q)foriinrange(nodes_at_level):x,y,d=q.popleft()ifx==n-1andy==n-1:returndforchoiceinchoices:n_x=x+choice[0]n_y=y+choice[1]# Check if suggested new cell is valid if-1<n_x<nand-1<n_y<nandvisited[n_x][n_y]==-1:visited[n_x][n_y]=d+1q.append((n_x,n_y,d+1))return-1
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
KnightL on a Chessboard
You are viewing a single comment's thread. Return to all comments →
Main Points - 1. Min path for knightL(a,b) will be same as knight(b, a). This observation reduces half of the processing 2. Think matrix as tree with root node at 0,0 and all possible next cell which can be taken from curr node as child. The BFS traversal will give the shorted path len.