We presented a complete, scalable implementation of an ( n \times n \times n ) Rubik’s Cube solver in Python, available on GitHub. The reduction method works for any ( n ) and is practical up to ( n=10 ) on standard hardware. The code is modular, tested, and includes parity handling and visualization.
The repository serves as both a learning tool for combinatorial algorithms and a foundation for further optimizations.
if name == "main": # Create a 3x3 cube cube3 = RubiksCubeNxN(3) print("Solved 3x3 cube:") print(cube3.to_string())
cube3.scramble(10)
print("\nScrambled 3x3 cube:")
print(cube3.to_string())
solver = RubiksCubeNxNSolver(cube3)
solver.solve()
# Create a 4x4 cube
cube4 = RubiksCubeNxN(4)
print("\n4x4 cube created (solved).")
This script defines a generic RubiksCube class. It handles the state management, specific moves for any $N$ (including wide moves for big cubes), and the logic to solve it.
Note: Writing a full heuristic search (like IDA*) from scratch for $N \times N \times N$ in a single script is extremely complex. This solution uses the "Reduction Method" strategy:
import kociemba import randomclass RubiksCubeNXN: def init(self, n): if n < 2: raise ValueError("Cube size must be at least 2x2x2") self.n = n self.reset()
def reset(self): """Initializes the solved state of the cube.""" # Faces: U, R, F, D, L, B # We represent the cube as a dictionary of 2D arrays self.faces = {} colors = ['W', 'R', 'G', 'Y', 'O', 'B'] # Standard color scheme for i, face_name in enumerate(['U', 'R', 'F', 'D', 'L', 'B']): self.faces[face_name] = [[colors[i]] * self.n for _ in range(self.n)] def rotate_face_clockwise(self, face_key): """Rotates a specific face matrix 90 degrees clockwise.""" self.faces[face_key] = [list(row) for row in zip(*self.faces[face_key][::-1])] def rotate_face_counter_clockwise(self, face_key): """Rotates a specific face matrix 90 degrees counter-clockwise.""" self.faces[face_key] = [list(row) for row in zip(*self.faces[face_key])][::-1] def move(self, notation): """ Parses and executes standard Rubik's notation. Supports: U, D, R, L, F, B (and primes ', 2, and wide moves like Uw, 3Uw) """ # Simple parser for demonstration # Mapping face names to internal keys face_map = 'U': 'U', 'D': 'D', 'R': 'R', 'L': 'L', 'F': 'F', 'B': 'B' # Parse the string prime = "'" in notation double = "2" in notation wide = "w" in notation # Extract depth for wide moves (e.g.,
Python is the language of choice for NxNxN cube algorithms because: