In a given 2d grid of positive integers (representing different types of "bubbles"), there are one of two actions that you can do each "step". You can either:
- Pop an island (a connected group of bubbles - two bubbles that are diagonally adjacent are not considered connected) of the same type of bubbles, given that the island consists of at least 2 bubbles AND at least one bubble in said island has no bubbles above it.
Or,
- Drop a single bubble of any type into any column, given that the chosen column is not filled to the top of the grid.
After one of these two steps, all bubbles will fall towards the bottom of the grid, and the next step will start.
The grid can also include 0
's, which represent empty space.
Task
Your task is: Given a \$m\times n\$ 2d grid of positive integers representing a grid of bubbles and the optional \$m\$ and \$n\$ and input, determine the fewest amount of moves in which the entire grid can be cleared of bubbles. The input grid is guaranteed to be clearable.
Worked example
22222
21212
22222
21212
22222
The first step will be to first pop the island of 2
's. After all the bubbles have fallen, the grid will then look like this, where the 0
's represent empty space:
00000
00000
00000
01010
01010
The second step will be to drop a 1
bubble in the middle column, so that the grid now looks like this:
00000
00000
00000
01010
01110
And the final step is to pop the island of 1
's, clearing the entire grid.
Test Cases
m, n
grid
-> output
5, 5
22222
21212
22222
21212
22222
-> 3
7, 7
1111111
2222222
1111111
2222222
1111111
2222222
1111111
-> 7
7, 6
000000
121212
212121
121212
212121
121212
212121
-> 22
2, 7
0000000
1000001
-> 4
8, 1
0
1
2
2
2
2
2
1
-> 5
8, 2
00
10
20
20
20
20
20
10
-> 4
If any of y'all need it, I also made a (pretty bad) tool that will take in a list of steps (more info in the TIO link) and output the board state after those steps have been taken: Try It Online!
This is code-golf, so the shortest solution in bytes for each language wins!