imashutosh51

Minimum Steps by Knight to reach target

Aug 11th, 2022 (edited)
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. '''
  2. Logic: T.C: O(n*n) ie. no. of blocks of chess board
  3.       BFS is used here.
  4. '''
  5.  
  6. cfrom math import inf
  7. from collections import deque
  8. def is_feasible(new_pos,n,visited):
  9.     if new_pos[0]>=0 and new_pos[0]<n and new_pos[1]>=0 and new_pos[1]<n and visited[new_pos[0]][new_pos[1]]==False:
  10.         return True
  11.     return False
  12.    
  13. class Solution:
  14.     def minStepToReachTarget(self, knightPos, targetPos, n):
  15.         if knightPos==targetPos:
  16.             return 0
  17.         ans=inf
  18.         q=deque()
  19.         visited=[[False]*n for j in range(n)]
  20.         i=knightPos[0]-1
  21.         j=knightPos[1]-1
  22.  
  23.         visited[i][j]=True
  24.         q.append([i,j,0])
  25.        
  26.         while len(q)>0:
  27.             k=len(q)
  28.             for z in range(k):
  29.                 x=[-2,-2,-1,1,2,2,1,-1]
  30.                 y=[-1,1,2,2,1,-1,-2,-2]
  31.                 temp=q.popleft()
  32.                 i,j,cur_dist=temp[0],temp[1],temp[2]
  33.                
  34.                 for k in range(8):
  35.                     new_i=i+x[k]
  36.                     new_j=j+y[k]
  37.                     if new_i==targetPos[0]-1 and new_j==targetPos[1]-1:
  38.                         return cur_dist+1
  39.                     if is_feasible([new_i,new_j],n,visited):
  40.                         q.append([new_i,new_j,cur_dist+1])
  41.                         visited[new_i][new_j]=True
  42.         return 0
  43.        
  44.        
  45.        
  46.        
  47.        
Advertisement
Add Comment
Please, Sign In to add comment