Advertisement
Nenogzar

Untitled

Feb 12th, 2024
1,270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. # Функция за намиране на началната позиция на "k" в лабиринта
  2. def find_position(maze):
  3.     position = []
  4.     for row in range(len(maze)):
  5.         for el in maze[row]:
  6.             if el == 'k':
  7.                 position.append(row)
  8.                 position.append(maze[row].find('k'))
  9.                 return position
  10.  
  11. # Функция за намиране на свободните позиции (' ') в лабиринта
  12. def next_free_spot(maze):
  13.     free_spots = []
  14.  
  15.     for row in range(len(maze)):
  16.         for el in range(len(maze[row])):
  17.             tmp = []
  18.             if maze[row][el] == ' ':
  19.                 tmp.append(row)
  20.                 tmp.append(el)
  21.                 free_spots.append(tmp)
  22.  
  23.     return free_spots
  24.  
  25. # Функция за намиране на пътя в лабиринта
  26. def find_path(position, next_free, maze):
  27.     moves = 0
  28.  
  29.     while next_free:
  30.         x1, x2 = next_free.pop(0)
  31.  
  32.         # Проверка за движение наляво
  33.         if position[0] == x1 and position[1] - x2 == 1:
  34.             position = [x1, x2]
  35.             moves += 1
  36.         # Проверка за движение надясно
  37.         elif position[0] == x1 and x2 - position[1] == 1:
  38.             position = [x1, x2]
  39.             moves += 1
  40.         # Проверка за движение надолу
  41.         elif x1 - position[0] == 1 and position[1] == x2:
  42.             position = [x1, x2]
  43.             moves += 1
  44.         # Проверка за движение нагоре
  45.         elif position[0] - x1 == 1 and position[1] == x2:
  46.             position = [x1, x2]
  47.             moves += 1
  48.  
  49.     # Проверка за излизане от лабиринта
  50.     if position[0] == 0 or position[0] == (len(maze) - 1) or position[1] == 0 or position[1] == len(maze[0]):
  51.         return f'Kate got out in {moves + 1} moves'
  52.    
  53.     return 'Kate cannot get out'
  54.  
  55.  
  56. m_rows = int(input())
  57. maze = []
  58. moves = 0
  59. free_space = True
  60.  
  61.  
  62. for row in range(m_rows):
  63.     maze.append(input())
  64.  
  65.  
  66. position = find_position(maze)
  67. next_free = next_free_spot(maze)
  68. movement = find_path(position, next_free, maze)
  69. print(movement)
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement