Guest User

Untitled

a guest
Jan 15th, 2025
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.00 KB | Source Code | 0 0
  1. import time
  2. from collections import deque
  3.  
  4. def get_possible_moves(board_tuple, empty_r, empty_c):
  5.     possible_moves = []
  6.     for dr, dc in [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)]:
  7.         r, c = empty_r + dr, empty_c + dc
  8.         if 0 <= r < 5 and 0 <= c < 5:
  9.             board = [list(row) for row in board_tuple]
  10.             if board[r][c] != 'E':
  11.                 next_board = [list(row) for row in board]
  12.                 next_board[empty_r][empty_c], next_board[r][c] = next_board[r][c], next_board[empty_r][empty_c]
  13.                 possible_moves.append((tuple("".join(row) for row in next_board), r, c, (r, c)))
  14.     return possible_moves
  15.  
  16.  
  17. def solve():
  18.     initial_board_tuple = (
  19.         "GBBBB",
  20.         "GGBBB",
  21.         "GGEBB",
  22.         "GGGBB",
  23.         "GGGGB"
  24.     )
  25.  
  26.     target_board_tuple = (
  27.        "BGGGG",
  28.        "GBBGG",
  29.        "GGEEG",
  30.        "GGGBB",
  31.        "GGGGB"
  32.     )
  33.  
  34.     def check_target(current_board_tuple):
  35.         return current_board_tuple == target_board_tuple
  36.    
  37.     max_estimated_states = 25 * (2**25)
  38.     queue = deque([(initial_board_tuple, 0, 2, 2, [])])  # (board, moves, empty_r, empty_c, path)
  39.     visited = {initial_board_tuple}
  40.     best_moves_found = float('inf')
  41.     nodes_checked = 0
  42.     update_frequency = 100
  43.     start_time = time.time()
  44.    
  45.     while queue:
  46.         current_board_tuple, moves, empty_r, empty_c, path = queue.popleft()
  47.         nodes_checked += 1
  48.  
  49.         if check_target(current_board_tuple):
  50.             if moves < best_moves_found:
  51.                 best_moves_found = moves
  52.                 print(f"Found a solution in {moves} moves", end='\r')
  53.                 print("\nSolution Path:")
  54.                 for i, (board, move_r, move_c) in enumerate(path):
  55.                     print_board(board, move_r, move_c, i)
  56.  
  57.             continue
  58.  
  59.         for next_board_tuple, next_empty_r, next_empty_c, move_pos in get_possible_moves(current_board_tuple, empty_r, empty_c):
  60.  
  61.              if next_board_tuple not in visited:
  62.                 visited.add(next_board_tuple)
  63.                 queue.append((next_board_tuple, moves + 1, next_empty_r, next_empty_c, path + [(current_board_tuple, move_pos[0], move_pos[1])]))
  64.                
  65.         if nodes_checked % update_frequency == 0:
  66.             percentage = min(100, (nodes_checked / max_estimated_states) * 100)
  67.             bar = "[" + "=" * int(percentage / 5) + " " * (20 - int(percentage / 5)) + "]"
  68.             elapsed_time = time.time() - start_time
  69.             if nodes_checked > 0:
  70.                 nodes_per_sec = nodes_checked / elapsed_time
  71.                 remaining_nodes = max_estimated_states - nodes_checked
  72.                 if nodes_per_sec > 0:
  73.                   eta_sec = remaining_nodes / nodes_per_sec
  74.                   eta_min = int(eta_sec / 60)
  75.                   eta_sec = int(eta_sec % 60)
  76.                   eta_str = f"{eta_min}m {eta_sec}s"
  77.                 else:
  78.                    eta_str = "N/A"
  79.  
  80.             else:
  81.                 eta_str = "N/A"
  82.  
  83.             print(f"Progress: {bar} {percentage:.2f}%, Visited: {nodes_checked}, Best: {best_moves_found if best_moves_found != float('inf') else 'N/A'}, Depth: {moves}, ETA: {eta_str}", end="\r")
  84.                
  85.     return best_moves_found if best_moves_found != float('inf') else -1
  86. def print_board(board_tuple, moved_r, moved_c, step):
  87.     """Prints the board with a colored move indication."""
  88.     colors = {
  89.         'G': '\033[92mG\033[0m',   # Green
  90.         'B': '\033[94mB\033[0m',    # Blue
  91.         'E': 'E'   # Empty
  92.     }
  93.     print(f"Step {step}:")
  94.     for r, row in enumerate(board_tuple):
  95.       colored_row = ""
  96.       for c, cell in enumerate(row):
  97.           if r == moved_r and c == moved_c:
  98.                 colored_row += f'\033[93m{colors.get(cell, cell)}\033[0m'  #Yellow for the moved piece
  99.           else:
  100.             colored_row += colors.get(cell, cell)
  101.       print(colored_row)
  102.  
  103.  
  104. result = solve()
  105. print(f"The smallest number of moves required is: {result}")
Add Comment
Please, Sign In to add comment