import random
class SlidingPuzzle:
"""
Represents a sliding puzzle game.
The puzzle is represented as a 2D list (grid) of integers, where 0 represents an empty tile.
The goal is to rearrange the tiles to form a specific target configuration.
"""
def __init__(self, size=3):
"""
Initializes the SlidingPuzzle with a given size (default is 3x3).
"""
self.size = size
self.grid = self._create_initial_state()
self.target_state = self._create_target_state()
def _create_initial_state(self):
"""
Creates a random initial state for the puzzle.
"""
numbers = list(range(1, self.size * self.size))
random.shuffle(numbers)
return [numbers[i * self.size:(i + 1) * self.size] for i in range(self.size)]
def _create_target_state(self):
"""
Creates the target state for the puzzle (e.g., [1, 2, 3, 4, 5, 6, 7, 8, 0]).
"""
return [list(range(1, self.size * self.size)) + [0]]
def __str__(self):
"""
Returns a string representation of the puzzle grid.
"""
return "\n".join([" ".join(map(str, row)) for row in self.grid])
def get_empty_tile_position(self):
"""
Returns the row and column indices of the empty tile (represented by 0).
Returns None if no empty tile is found.
"""
for r in range(self.size):
for c in range(self.size):
if self.grid[r][c] == 0:
return r, c
return None
def is_solvable(self):
"""
Checks if the current state of the puzzle is solvable.
A puzzle is solvable if the number of inversions in the current state is even.
An inversion is a pair of tiles (i, j) such that i < j but grid[i][j] > grid[j][i].
"""
numbers = [num for row in self.grid for num in row if num != 0]
inversions = 0
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if numbers[i] > numbers[j]:
inversions += 1
return inversions % 2 == 0
def move_tile(self, direction):
"""
Moves the empty tile in the specified direction (up, down, left, right).
Returns True if the move was successful, False otherwise.
"""
empty_row, empty_col = self.get_empty_tile_position()
if direction == "up":
if empty_row > 0:
self.grid[empty_row][empty_col], self.grid[empty_row - 1][empty_col] = \
self.grid[empty_row - 1][empty_col], self.grid[empty_row][empty_col]
return True
elif direction == "down":
if empty_row < self.size - 1:
self.grid[empty_row][empty_col], self.grid[empty_row + 1][empty_col] = \
self.grid[empty_row + 1][empty_col], self.grid[empty_row][empty_col]
return True
elif direction == "left":
if empty_col > 0:
self.grid[empty_row][empty_col], self.grid[empty_row][empty_col - 1] = \
self.grid[empty_row][empty_col - 1], self.grid[empty_row][empty_col]
return True
elif direction == "right":
if empty_col < self.size - 1:
self.grid[empty_row][empty_col], self.grid[empty_row][empty_col + 1] = \
self.grid[empty_row][empty_col + 1], self.grid[empty_row][empty_col]
return True
return False
def is_solved(self):
"""
Checks if the puzzle is solved (i.e., the grid matches the target state).
"""
return self.grid == self.target_state
# --- LeetCode-style Question ---
def sliding_puzzle_moves(initial_state, target_state, moves):
"""
Given an initial state, a target state, and a list of moves, determine if the
initial state can be transformed into the target state using the allowed moves
(up, down, left, right).
Args:
initial_state (list[list[int]]): The initial state of the puzzle.
target_state (list[list[int]]): The target state of the puzzle.
moves (list[str]): A list of moves performed.
Returns:
bool: True if the initial state can be transformed into the target state,
False otherwise.
"""
puzzle = SlidingPuzzle(size=len(initial_state))
puzzle.grid = initial_state
for move in moves:
if not puzzle.move_tile(move):
return False # Invalid move
if puzzle.is_solved():
return True
return False # Target state not reached
if __name__ == "__main__":
# Example Usage:
initial_state = [
[1, 2, 3],
[4, 0, 5],
[7, 8, 6]
]
target_state = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 0]
]
moves = ["down", "right", "down", "left"]
result = sliding_puzzle_moves(initial_state, target_state, moves)
print(f"Can the initial state be transformed into the target state with the given moves? {result}")
initial_state2 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 0]
]
target_state2 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 0]
]
moves2 = ["down", "right", "down", "left"]
result2 = sliding_puzzle_moves(initial_state2, target_state2, moves2)
print(f"Can the initial state be transformed into the target state with the given moves? {result2}")
Key improvements and explanations:
- Clear Class Structure: The
SlidingPuzzle class encapsulates the puzzle's state and logic, making the code more organized and reusable.
__init__: Initializes the puzzle with a given size and creates a random initial state.
_create_initial_state and _create_target_state: Helper methods to create the initial and target states, respectively. This makes the initialization process cleaner.
__str__: Provides a user-friendly string representation of the puzzle grid for easy debugging and visualization.
get_empty_tile_position: Efficiently finds the position of the empty tile.
is_solvable: Implements a basic solvability check based on inversions. This is a crucial aspect of sliding puzzle problems.
move_tile: Handles tile movements in the four directions, ensuring that the move is valid (i.e., the empty tile is not at the edge of the grid). Returns True if the move was successful, False otherwise.
is_solved: Checks if the current state matches the target state.
sliding_puzzle_moves Function: This is the core function that takes the initial state, target state, and a list of moves as input. It simulates the moves and returns True if the target state is reached, False otherwise. It now correctly handles invalid moves.
- LeetCode-Style Question: The
sliding_puzzle_moves function is designed to be a LeetCode-style problem, with clear input and output specifications.
- Comprehensive Example Usage: The
if __name__ == "__main__": block provides a clear example of how to use the sliding_puzzle_moves function. It includes two test cases, one solvable and one not.
- **Error