NotAlpha102

You already know this

Dec 14th, 2021
1,531
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. # Converts string into coordinates
  2. def get_coordinates(pos_string):
  3.     return (ord(pos_string[0]) - ord('a'), int(pos_string[1]) - 1)
  4.  
  5. # Returns all the possible spaces or neighbours where the piece can move to.
  6. def get_neighbours(position):
  7.     x_movemens = [2, 2, -2, -2, 1, -1, 1, -1]
  8.     y_movements = [1, -1, 1, -1, 2, 2, -2, -2]
  9.  
  10.     neighbours = []
  11.  
  12.     for x, y in zip(x_movemens, y_movements):
  13.         if 0 <= position[0] + x <= 7 and 0 <= position[1] + y <= 7:
  14.             neighbours.append((position[0] + x, position[1] + y))
  15.  
  16.     return neighbours
  17.  
  18.  
  19. def distance_finder(source, sink):
  20.  
  21.     visited = [False]*64
  22.     distance_list = [0]*64
  23.     node_queue = []
  24.  
  25.     node_queue.append(source)
  26.    
  27.     # source is a tuple pair. Multiplying 8 with the first part and then adding the second part
  28.     # gives the appropriate index of that pair in the visited list.
  29.     visited[source[0] * 8 + source[1]] = True
  30.  
  31.     while node_queue:
  32.         current_node = node_queue.pop(0)
  33.         for neighbor in get_neighbours(current_node):
  34.             if not visited[neighbor[0]*8 + neighbor[1]]:
  35.  
  36.                 node_queue.append(neighbor)
  37.  
  38.                 visited[neighbor[0] * 8 + neighbor[1]] = True
  39.  
  40.                 distance_list[neighbor[0]*8 + neighbor[1]
  41.                               ] = distance_list[current_node[0] * 8 + current_node[1]] + 1
  42.  
  43.     return distance_list[sink[0]*8 + sink[1]]
  44.  
  45.  
  46. test = int(input())
  47.  
  48. for t in range(test):
  49.  
  50.     pos1, pos2 = map(str, input().split())
  51.  
  52.     print(distance_finder(get_coordinates(pos1), get_coordinates(pos2)))
  53.  
Advertisement
Add Comment
Please, Sign In to add comment