Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Logic: T.C: O(n*n) ie. no. of blocks of chess board
- BFS is used here.
- '''
- cfrom math import inf
- from collections import deque
- def is_feasible(new_pos,n,visited):
- 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:
- return True
- return False
- class Solution:
- def minStepToReachTarget(self, knightPos, targetPos, n):
- if knightPos==targetPos:
- return 0
- ans=inf
- q=deque()
- visited=[[False]*n for j in range(n)]
- i=knightPos[0]-1
- j=knightPos[1]-1
- visited[i][j]=True
- q.append([i,j,0])
- while len(q)>0:
- k=len(q)
- for z in range(k):
- x=[-2,-2,-1,1,2,2,1,-1]
- y=[-1,1,2,2,1,-1,-2,-2]
- temp=q.popleft()
- i,j,cur_dist=temp[0],temp[1],temp[2]
- for k in range(8):
- new_i=i+x[k]
- new_j=j+y[k]
- if new_i==targetPos[0]-1 and new_j==targetPos[1]-1:
- return cur_dist+1
- if is_feasible([new_i,new_j],n,visited):
- q.append([new_i,new_j,cur_dist+1])
- visited[new_i][new_j]=True
- return 0
Advertisement
Add Comment
Please, Sign In to add comment