Download as pdf
Download as pdf
You are on page 1of 5
tora, 987 AM Chet Kh Probl Fn the shore path om sou odstnaon— Tah Del TECHIE DELIGHT Q FAANG Interview Prep Practice "°" Data Structures and Algorithms ¥ Chess Knight Problem | Find the shortest path from source to destination Given a chessboard, find the shortest distance (minimum number of steps) taken by a knight to reach a given destination from a given source. For example, Input: N= 8 (8 x 8 board) Source = (7, @) Destination = (8, 7) Output: Minimum number of steps required is 6 The knight's movement is illustrated in the following figure’ hitpsi ww techiedelight. com/chess-knight-problem-find-shortest-path-source-destination! 16 12119921, 9:57 AM ‘Chess Knight Problem | Find the shortest path fom source to destination — Techie Deligh Practice this problem ‘The idea is to use Breadth-first search (BFS) as it is the shortest path problem. Following is the complete algorithm 1. Create an empty queue and enqueue the source cell having a distance of 0 from the source (itself. 2. Loop till queue is empty: | Dequeue next unvisited node. IL If the popped node is the destination node, return its distance. Ill Otherwise, we mark the current node as visited. For each of eight possible movements for a knight, enqueue each valid movement with +1 distance (minimum distance of a given node from the source is one more than the minimum distance of parent from source) A knight can move in eight possible directions from a given cell as illustrated in the following figure: We can find all the possible locations the knight can move to from the given location by using the array that stores the relative position of knight movement from any location. For example, if the kee? current location is (x, y) ,we can move to (x + row[k], y + col[k]) for using the following array: row] = [ 2, 2, -2, -2, 1, 1, -1, -1] colf] = [ -1, 4, 1, -1, 2, -2, 2, -2] hitpsi ww tachiedelight. com/chess-knight-problem-find-shortest-path-source-destination! 218 12119921, 9:57 AM ‘chess Knight Problem | Find the shortest path rom source to destination — Techie Delight So, from position (x, y) knight's can move to’ (+2 y-4) (+2 y+) (-2 y+) Qe - 2, y - 1) (x +1, y + 2) (+4, y- 2) (4, y +2) (x- 4, y - 2) Note that in BFS, all cells having the shortest path as 1 are visited first, followed by their adjacent cells having the shortest path as 1 + 1 = 2 and so on... so if we reach any node in BFS, its shortest path = shortest path of parent + 1. So, the destination cell's first occurrence gives us the result, and we can stop our search there. The shortest path cannot exist from some other cell for which we haven't reached the given node yet. If any such path were possible, we would have already explored i The algorithm can be implemented as follows in C+ +, Java, and Python: CH ~ Java v Python 1 | import sys 2 | fron collections import deque 3 4 5 | # A queue node used in BFS 6 | class Node: 7 # (x, y) represents chessboard coordinates 8 # ‘dist’ represents its minimum distance from the source 9 def _init_(self, x, y, dist-@): 10 self.x = x rte self.y =y 2 self.dist = dist 3B 14 # As we are using “Node” as a key in a dictionary, a5 # we need to override the “_hash_()° and *_eq_()° function 16 def _hash_(self): v7 return hash((self.x, self.y, self.dist)) 18 19 def _eq_(self, other): 20 return (self.x, self.y, self.dist) == (other.x, other.y, other.dist) 2 2 23 | # Below lists detail all eight possible movements for a knight 24 [2, 2, -2, -2, 1, 4, -1, -1] 25 » 4,1, -1, 2, -2, 2, -2] 26 27 28 | # Check if (x, y) is valid chessboard coordinates. 29 | # Note that a knight cannot go out of the chessboard tps ww techiedelight. comichess-knight-problemsfind-shortest-path-source-destinaion! as 12119921, 9:57 AM ‘chess Knight Problem | Find the shortest path rom source to destination — Techie Delight 30 | def isvalid(x, y, N): 31 return not (x < @ or y < @ or x >= Nor y >= N) 32 33 34 | # Find the minimum number of steps taken by the knight 35 | # from the source to reach the destination using BFS 36 | def findShortestDistance(src, dest, N): 37 38 # set to check if the matrix cell is visited before or not 39 visited = set() 40 a # create a queue and enqueue the first node a2 q = deque() 43 q-append(sre) 44 45 # loop till queue is empty 46 while q: 47 48 # dequeue front node and process it 49 node = q.popleft() 50 51 x = node.x 52 y = node.y 53 Gist = node.dist 54 55 # if the destination is reached, return distance 56 if x == dest.x and y == dest.y: 57 return dist 58 59 # skip if the location is visited before 60 if node not in visited: 61 # mark the current node as visited 62 visited. add(node) 63 64 # check for all eight possible movements for a knight 65 # and enqueue each valid movement 66 for i in range(1en(row)): 67 # get the knight's valid position from the current position ¢ 68 # the chessboard and enqueue it with +1 distance 69 x1 = x + row[i] 76 yl = y + colli] n 2 if isvalid(xt, yt, B @.append(Node(x1, y1, dist + 1)) 74 B # return infinity if the path is not possible 76 return sys.maxsize 7 8 79 if _name_ == '_main_': 80 81 N=8 #N XN matrix 82 src = Node(@, 7) # source coordinates 83 dest = Node(7, @) # destination coordinates 84 85 print ("The minimum number of steps required is*, 86 ‘findShortestDistance(sre, dest, N)) 87 Download Run Code output: The minimum number of steps required is 6 The time complexity of the proposed solution is O(M * N) and requires O(M x N) extra space, where M and N are dimensions of the matrix. hips: techiedstight con/chess-Anightprlem-ind-shortest-pa-soure- destination! 4s 12119921, 9:57 AM ‘chess Knight Problem | Find the shortest path rom source to destination — Techie Delight Exercise: Extend the solution to print the paths as well & Graph, Matrix, Queue # Algorithm, Breadth-first search, FIFO, Hard Privacy Policy | Send feedback Techie Delight © 2021 All Rights Reserved. hitpsi ww techiedeligh. comchess-knight-problen-find-shortest-path-source-destnaion! 5s

You might also like