20
3
Input:
A matrix containing integers in the range [0 - 9].
Challenge:
Determine if all non-zero elements are connected to each other vertically and/or horizontally.
Output:
A truthy value if all are connected, and a falsy value if there are non-zero elements/groups that aren't connected to other elements/groups.
Test cases:
Test cases are separated by line. Test cases can be found in more convenient formats here (Kudos to Dada).
The following are all connected and should return a truthy value:
0
---
0 0
---
1 1 1
0 0 0
---
1 0 0
1 1 1
0 0 1
---
0 0 0 0 0 0
0 0 3 5 1 0
0 1 0 2 0 1
1 1 0 3 1 6
7 2 0 0 3 0
0 8 2 6 2 9
0 0 0 0 0 5
The following are all not-connected, and should return a falsy value:
0 1
1 0
---
1 1 1 0
0 0 0 2
0 0 0 5
---
0 0 5 2
1 2 0 0
5 3 2 1
5 7 3 2
---
1 2 3 0 0 5
1 5 3 0 1 1
9 0 0 4 2 1
9 9 9 0 1 4
0 1 0 1 0 0
This is code-golf, so the shortest submission in each language wins. Explanations are encouraged!
Inspired by this challenge.
Perhaps the input should contain only ones and zeros (or truthys and falsys), as this is essentially about connected components. – NikoNyrh – 2018-01-30T14:15:33.953
Can we take input as an 1d array and a number of columns? – ovs – 2018-01-30T15:05:22.140
@ovs sure. I can't see that it should give you any advantages over other people that have already answered. – Stewie Griffin – 2018-01-30T17:06:09.890
3Related: how many zeroes do you need to change to make all nonzero elements connected – dylnan – 2018-01-30T17:34:50.930
Related: count the number of components (but with diagonal entries adjacent). – Misha Lavrov – 2018-02-05T14:53:33.017