Consider binary block diagonal matrices which have square blocks of 1s on the main diagonal, and are 0 everywhere else. Let's call such matrices "valid" matrices.
For example, here are some valid 4x4 matrices:
1 0 0 0 1 1 0 0 1 0 0 0 1 0 0 0 1 1 0 0 1 1 1 1
0 1 0 0 1 1 0 0 0 1 1 0 0 1 1 1 1 1 0 0 1 1 1 1
0 0 1 0 0 0 1 0 0 1 1 0 0 1 1 1 0 0 1 1 1 1 1 1
0 0 0 1 0 0 0 1 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1
Note that an alternative way of describing such matrices is that there is a chain of square 1 blocks from the top-left to the bottom-right, touching corner to corner, and everywhere else is 0.
For contrast, here are some invalid 4x4 matrices:
1 0 1 0 1 0 1 0 1 1 0 0 0 1 1 1 1 1 0 0 0 0 0 0
0 1 1 1 0 1 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 0 0
1 0 0 1 1 0 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0
0 0 1 0 0 1 0 1 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0
You will be given an n
by n
binary matrix as input – what is the minimum number of 0
bits you'll need to set to 1
in order to get a valid matrix?
You may write a function or program taking in any convenient string, list or matrix format representing an n
by n
matrix of 0s and 1s (as long as it isn't preprocessed). Rows must be clearly separated in some way, so formats like a 1D array of bits are not allowed.
This is code-golf, so the goal is to minimise the number of bytes in your program.
Examples
For example, if the input is
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 1
then the answer is 5, since you can set five 0
bits to 1
to get:
1 0 0 0 0
0 1 1 0 0
0 1 1 0 0
0 0 0 1 0
0 0 0 0 1
and this is the minimum number required. However, if the input was
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
then the answer is 24, since the only valid 5x5 matrix where the top-right is 1
is the matrix of all 1
s.
Test cases
Tests are represented here as a 2D array of integers.
[[0]] -> 1
[[1]] -> 0
[[0,1],[0,0]] -> 3
[[1,0],[0,0]] -> 1
[[0,0,0],[0,1,0],[0,0,0]] -> 2
[[0,1,0],[0,0,0],[0,1,0]] -> 7
[[0,1,0],[1,0,0],[0,0,1]] -> 2
[[1,1,1],[1,1,1],[1,1,1]] -> 0
[[0,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,0]] -> 4
[[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] -> 8
[[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,0,1,0]] -> 14
[[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,1,0,0]] -> 14
[[0,0,0,0,0],[0,0,0,0,0],[0,1,0,0,0],[0,0,0,0,1],[0,0,0,0,0]] -> 7
[[0,0,0,0,0],[0,0,0,0,0],[1,0,0,0,0],[0,0,0,0,1],[0,0,0,0,0]] -> 11
[[0,0,0,0,0],[0,0,1,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,1]] -> 5
[[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] -> 24
[[0,0,0,1,0],[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] -> 23
[[0,1,0,0,0],[1,0,0,0,0],[0,0,1,0,0],[0,0,0,0,1],[0,0,0,1,0]] -> 4
[[0,1,1,1,0],[0,1,1,0,1],[0,1,1,1,0],[0,1,0,0,1],[0,0,0,0,0]] -> 14
Notes
- Related challenge: Print a Block-Diagonal Matrix
- Inspiration: Freedom Factory, Google Code Jam 2016 Problem 2D