11
Let's imagine we have a matrix of bits (which contains at least one 1
):
0 1 0 1 1 0 1 0 0 1 0
0 1 0 1 0 0 1 0 1 1 0
0 0 1 0 1 1 0 1 0 1 0
1 1 0 0 1 0 0 1 1 0 1
0 0 0 1 0 1 1 0 0 1 0
We want to set some of the bits in this matrix such that it forms a contiguous blob of 1
s, in which every 1
is directly or indirectly connected to every other 1
through orthogonal movement:
0 1 1 1 1 1 1 0 0 1 0
0 1 0 1 0 0 1 0 1 1 0
0 1 1 0 1 1 1 1 0 1 0
1 1 0 0 1 0 0 1 1 1 1
0 0 0 1 1 1 1 0 0 1 0
(You can see this more clearly by searching for 1
with your browser's "find" feature.)
However, we also want to minimize the number of bits that we set.
The Task
Given a matrix (or array of arrays) of bits or booleans, return the minimum number of bits that need to be set to create a contiguous continent of 1
s. It should be possible to get from one set bit in the matrix to another by only traveling in an orthogonal direction to other set bits.
This is code-golf, so the shortest valid submission (measured in bytes) wins.
Test Cases
0 1 0 1 1 0 1 0 0 1 0
0 1 0 1 0 0 1 0 1 1 0
0 0 1 0 1 1 0 1 0 1 0
1 1 0 0 1 0 0 1 1 0 1
0 0 0 1 0 1 1 0 0 1 0
=> 6
1 0 0 0 0 0 1 0 0
1 1 0 0 1 1 1 0 0
1 1 1 0 1 1 1 1 1
0 1 0 0 0 0 0 0 0
0 0 0 0 0 1 1 1 1
0 1 0 0 0 0 1 1 0
1 0 0 0 0 0 1 0 0
=> 4
0 0 0 1 1 1 0 1 1
0 0 1 0 0 0 0 1 0
0 0 1 1 1 1 1 1 0
1 1 0 0 1 1 0 0 0
0 0 1 1 1 0 0 1 1
0 1 1 1 0 0 0 0 0
1 1 1 0 0 1 1 1 0
1 1 1 0 1 1 0 1 1
0 0 0 0 1 0 0 0 1
1 1 0 0 1 1 0 1 1
0 0 0 0 0 0 0 1 0
0 1 1 1 1 0 0 0 0
0 0 0 1 1 0 0 0 1
0 1 0 0 1 0 1 1 0
0 1 1 1 0 0 0 0 1
=> 8
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
=> 0
1This needs a bit more explaining. What is a "contiguous blob" in a matrix? – NoOneIsHere – 2017-10-06T05:59:33.863
What are the parameters in which we express the complexity? – xnor – 2017-10-06T06:08:57.453
@xnor What do you mean by this? – Esolanging Fruit – 2017-10-06T06:14:04.943
@Challenger5 Never mind, I see you added "(in the number of bits in the matrix)" regarding the time complexity. – xnor – 2017-10-06T06:15:12.467
11
Since the problem is known to be NP-hard it's not a good problem for [tag:fastest-algorithm].
– Peter Taylor – 2017-10-06T07:24:07.403Is it just me or is this the TSP in disguise – HyperNeutrino – 2017-10-06T12:11:58.673
@PeterTaylor This challenge just asks to find how many bits need to be set, not what bits to set. Would that make a difference? – Esolanging Fruit – 2017-10-06T18:49:31.923
Unlikely in the general case, and no in this case.
– Peter Taylor – 2017-10-06T20:34:36.7731
@Peter Taylor and esolangingfruit NP-Hardness
– FantaC – 2017-12-12T03:24:59.9901In light of Peter Taylor and HyperNeutrino's comments, and the fact that the question currently has no answers, I'm changing the scoring method to [tag:code-golf]. – Esolanging Fruit – 2017-12-12T03:31:23.990
1What should we do if there's no
1
in the matrix? – Colera Su – 2017-12-12T08:04:33.8071@ColeraSu You don't have to handle that case. – Esolanging Fruit – 2017-12-12T15:19:53.757