Moving Marbles
Time limit0.5sMemory limit1024 MB
Given start and target 0/1 grids, find the fewest moves to reach the target by sliding, removing, or placing marbles. Print -1 if impossible.
- Level
Medium7 of 10
- Topics
- Graph, Shortest path
- Solved
- No attempts yet
Moving Marbles
Hanseo has a board with rows and columns. Each cell may hold a marble, shown as 1 if the cell has a marble and 0 if it is empty. Given the initial state of the board, Hanseo wants to rearrange the marbles into a target pattern. Moving marbles is tedious for him, so he wants to use as few moves as possible.
In one move, Hanseo can do one of the following three actions.
- Move a marble to one of the 4 adjacent empty cells (up, down, left, right). A marble cannot be moved outside the board.
- Remove a marble from a cell of his choice and store it. There is no limit on how many marbles he can store, but when the target pattern is complete, he must have no stored marbles left.
- Place one of the stored marbles on an empty cell of his choice.
If the target pattern cannot be completed, print -1. Otherwise, print the minimum number of moves needed to complete it.