10
Input:
A 2D array containing two distinct (optional) values. I'll use 0 and 1 when explaining the rules. The input format is of course flexible.
Challenge:
Zeros are water, and ones are islands. In order to ensure loneliness, your task is to surround all islands with water by inserting rows and columns of zeros. You don't want to waste water, so you must minimize the amount of water added. In case there are more than one solution that requires the same amount of water added, then you should add columns of water, not rows. I'll show this in the test cases.
Output:
The new, modified 2D array. The output format is of course flexible.
Test cases:
Input and output are separated by dashes. Added zeros are shown in bold font. Use one of the answers here if you want to convert the test cases to more convenient formats.
1
---
1
1 1
---
1 0 1
1 1
1 1
---
1 0 1
0 0 0
1 0 1
1 0
0 1
---
1 0 0
0 0 1
Note that we added a column of zeros, not a row of zeros. This is because the number of necessary zeros is equal, and columns should be preferred.
1 0 0 0 1
0 1 0 1 0
0 0 1 0 0
0 1 0 1 0
---
1 0 0 0 1
0 0 0 0 0
0 1 0 1 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 1 0 1 0
Note that we added rows, not columns, since that requires the least amount of extra zeros.
0 0 1 0 0
0 1 1 1 0
---
0 0 0 1 0 0 0
0 0 0 0 0 0 0
0 1 0 1 0 1 0
This required both columns and a row.
0 0 1 0 0
0 1 0 1 0
---
0 0 0 1 0 0 0
0 1 0 0 0 1 0
Better to add two columns than one row, since it requires less water.
0 0
1 0
0 1
1 0
0 0
---
0 0
1 0
0 0
0 1
0 0
1 0
0 0
Better to add two rows than one column, since it requires less water.
Related. – Stewie Griffin – 2018-04-10T09:00:06.467
Damnit, Stewie, now I've got "Jack Sparrow" stuck in my head again! – Shaggy – 2018-04-10T10:21:23.737
This problem is equivalent to the vertex cover problem on bipartite graph, and according to Wikipedia it can be solved in polynomial time.
– user202729 – 2018-04-10T11:13:46.373I changed my mind... it may be weighted. Anyway for sufficiently large square matrix it's (hopefully) equivalent. So if your algorithm is "too simple", be careful. – user202729 – 2018-04-10T15:40:57.740
I think I have a polynomial time algorithm. – user202729 – 2018-04-13T16:31:18.180