from collections import deque def min_moves_bfs(xf,yf,a,b,visited,q): while q: (x,y,num_moves) = q.popleft() found = enqueue_4_neighbors(x,y,a,b,visited,q,num_moves+1,xf,yf) if found!=-1: return found if (a!=b): found = enqueue_4_neighbors(x,y,b,a,visited,q,num_moves+1,xf,yf) if found!=-1: return found return -1 def enqueue_4_neighbors(x,y,a,b,visited,q,num_moves,xf,yf): if (x-a>=0) and (y-b>=0) and not visited[x-a][y-b]: q.append((x-a,y-b,num_moves)) visited[x-a][y-b] = True if q[-1][0]==xf and q[-1][1]==yf: return q[-1][2] if (x+a=0) and not visited[x+a][y-b]: q.append((x+a,y-b,num_moves)) visited[x+a][y-b] = True if q[-1][0]==xf and q[-1][1]==yf: return q[-1][2] if (x-a>=0) and (y+b