Let's assume that you get the following array:
foo = [
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,1,1,1,1,0,0],
[0,0,0,1,0,0,0,1,0,0],
[0,0,0,1,0,0,0,1,0,0],
[0,0,0,1,1,1,0,1,0,0],
[0,0,0,0,0,1,0,1,0,0],
[0,0,0,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
]
How can I determine if the pattern of 1s is a closed loop? I have struggled with this for a few days. I have tried a recursive loop to find neighbors and words, but when you have a more complex pattern it won't work, for example:
foo = [
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,1,1,0,0,0,0],
[0,0,0,1,0,1,0,0,0,0],
[0,0,0,1,0,1,0,0,0,0],
[0,0,0,1,1,1,1,1,0,0],
[0,0,0,0,0,1,0,0,0,0],
[0,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,0,0,0,0],
]
Do someone have a magic algorithm to solve this ? :(
As Dagrooms said, try to find 1(s) with only one adjacent 1. Code looks like:
where rows and columns are the 2d array size.
UPDATE
This will return true if there is at least one closed loop:
JSFiddle: https://jsfiddle.net/AdminXVII/b0f7th5d/
UPDATE 2 Extract the loop(s):
JSFiddle: https://jsfiddle.net/AdminXVII/b0f7th5d/7/
UPDATE 3
This is to threat if there's more than one loop, thougth for one loop it's slower.
JSFiddle: https://jsfiddle.net/AdminXVII/w7zcgpyL/
UPDATE 4
Safer
numTouching1()
method:Modified previous JSFiddle