Problem Description
We are given an 8 x 8 chessboard with n pieces (rooks, queens, or bishops) placed at distinct 1-based coordinates. Each piece must make a move simultaneously toward a chosen destination square obeying its movement rules. Every second all pieces move one square along the pre-determined straight path toward their destination. A move combination is the set of chosen destinations for all pieces. A combination is invalid if at any second two or more pieces are in the same square (note that adjacent pieces may swap positions, so crossing paths is allowed if they never share a square at the same time). Return the number of valid move combinations.
Key Insights
- Each piece has its own set of allowed destinations, determined by its movement rules (including staying in place).
- For each move option we precompute the list (path) of squares that the piece traverses (from the starting square to the destination).
- All pieces are moved simultaneously; simulation is done second by second until every piece has reached its destination.
- Because n ≤ 4, we can use backtracking to generate every combination of destination selections and simulate their moves.
- At every time step during simulation we check for collisions—if two or more pieces are in the same square, that combination is invalid.
Space and Time Complexity
Time Complexity: O(Choices^n * L) where Choices is the number of move options per piece (limited by board size) and L is the maximum length of the movement path (at most 8), with n ≤ 4. Space Complexity: O(n * ChoicePaths) due to storing the precomputed paths.
Solution
For each piece, generate a list of valid target positions and simulate the path to that target using the allowed directions. Store both the destination and the full step-by-step path (including the starting square). Then, using backtracking, select one move for each piece. For each move combination, simulate the simultaneous movement tick by tick (each tick represents one square movement for each piece) up to the maximum number of steps required by any piece. At each simulated tick, check if any two pieces occupy the same square. If not, count this combination as valid. This brute-force approach works due to the small constraint on n (n ≤ 4).
Code Solutions
Below are code solutions in Python, JavaScript, C++, and Java with inline comments.