12
1
Consider depicting a simple, open, two-dimensional curve on a W wide by H high grid of text where X represents part of the curve and . represents empty space and no other characters are used.
Every grid space has 8 neighboring grid spaces, its Moore neighborhood. Grid spaces beyond the borders are considered empty.
A grid contains a curve if it has exactly one X OR if it has more than one X where:
- Exactly two
Xs have only one neighboringX. These are the curve's endpoints. - Every
Xbesides the endpoints neighbors exactly twoXs. These form the bulk of the curve.
For example, this grid where W = 9 and H = 4 contains a curve:
....X.... .X.X.X.X. X..X..X.X .XX.....XLikewise, these grids (W = 4, H = 3) have curves:
.... .X.. .... .... .X.X .... X..X ..X. XX.. X.X. ..X. .XX. .X.. .... ....These grids, however, do not contain a curve:
.... .XX. ...X XX.. .... X.X. .... X..X ..XX XX.. .X.X .X.. .... .XX. .X.. .... ...X X.X.
We can find the length of a curve by summing the distances between all neighboring pairs of Xs:
The distance between two orthogonally neighboring
Xs is 1 unit.XXX XThe distance between two diagonally neighboring
Xs is √2 units.X. .X.X X.
For example, the length of the curve in the grid
XXX. ...X ..X.can be visualized as
so we can see it is 1 + 1 + √2 + √2 = 4.828427...
The length of a curve with only one X is zero.
When a grid does not form a curve its length is not well defined.
Challenge
Given a grid of text of Xs and .s, output the length of the curve it contains, or else output something such as -1 or Null to indicate the grid has no curve.
For input you may use other characters than X and . if desired, and H and W may be taken as input if needed. Input as a nested list or matrix filled with 1s and 0s instead of a string is also fine.
You may output a float for the curve length or alternatively two integers A and B where length = A + B*√2.
The shortest code in bytes wins.
Test Cases
XXX.
...X
..X.
2 + 2*√2 = 4.828427...
....X....
.X.X.X.X.
X..X..X.X
.XX.....X
3 + 8*√2 = 14.313708...
....
....
..X.
0 + 0*√2 = 0
.X..
X..X
.XX.
1 + 3*√2 = 5.242640...
....
..X.
.X..
0 + 1*√2 = 1.414213...
....
XX..
....
1 + 0*√2 = 1
.X.X
X.X.
....
0 + 3*√2 = 4.242640...
....
....
....
....
-1
.XX.
X..X
.XX.
-1
...X
..XX
.X..
-1
....
.X.X
...X
-1
X.X.
.X..
X.X.
-1

I recommend allowing the solver to choose their output format for grids that have no curves (any consistent value that's not of the form m + n*sqrt(2) for any m,n≥0). – Greg Martin – 2017-03-13T23:50:33.963
@Greg Sounds fine. Done – Calvin's Hobbies – 2017-03-14T03:17:58.530
[x.x,...,.x.]isn't a valid curve, right? – Magic Octopus Urn – 2017-03-14T14:57:23.977@carusocomputing correct – Calvin's Hobbies – 2017-03-14T14:58:31.870