Advertisement
Hasli4

bucktrack10

Mar 27th, 2025
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.98 KB | None | 0 0
  1. def read_maze(filename):
  2.     """Чтение лабиринта из файла"""
  3.     with open(filename, 'r') as f:
  4.         return [list(line.strip().split()) for line in f]
  5.  
  6. def solve_maze(maze, mouse_x, mouse_y, cheese_x, cheese_y):
  7.     """Решение лабиринта с подсчетом путей"""
  8.     N = len(maze)
  9.     visited = [[False for _ in range(N)] for _ in range(N)]
  10.  
  11.     def is_valid_move(x, y):
  12.         """Проверка корректности движения"""
  13.         return (
  14.             0 <= x < N and
  15.             0 <= y < N and
  16.             maze[x][y] == ' ' and
  17.             not visited[x][y]
  18.         )
  19.  
  20.     def find_paths(x, y):
  21.         """Рекурсивный поиск путей"""
  22.         # Достижение сыра
  23.         if x == cheese_x and y == cheese_y:
  24.             return 1
  25.  
  26.         # Отмечаем клетку как посещенную
  27.         visited[x][y] = True
  28.        
  29.         paths = 0
  30.         # Возможные направления: вверх, вправо, вниз, влево
  31.         moves = [(-1, 0), (0, 1), (1, 0), (0, -1)]
  32.        
  33.         for dx, dy in moves:
  34.             next_x, next_y = x + dx, y + dy
  35.            
  36.             if is_valid_move(next_x, next_y):
  37.                 paths += find_paths(next_x, next_y)
  38.        
  39.         # Возвращаем клетку в непосещенное состояние
  40.         visited[x][y] = False
  41.        
  42.         return paths
  43.  
  44.     return find_paths(mouse_x, mouse_y)
  45.  
  46. def main():
  47.     # Чтение лабиринта
  48.     maze = read_maze('maze.txt')
  49.    
  50.     # Координаты мышки и сыра
  51.     mouse_x, mouse_y = 1, 1  # Начальная позиция мышки
  52.     cheese_x, cheese_y = 3, 3  # Позиция сыра
  53.    
  54.     # Подсчет путей
  55.     paths = solve_maze(maze, mouse_x, mouse_y, cheese_x, cheese_y)
  56.     print(f"Количество путей: {paths}")
  57.  
  58. if __name__ == "__main__":
  59.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement