problems / 218

ASCII Polygon Area

easy geometry parsing matrix 1000 ms · 256 MB

ASCII Polygon Area

An ASCII-art drawing shows a simple polygon with vertices marked by * characters and edges drawn with -, |, /, or \ characters. The grid is indexed with row 0 at the top and column 0 at the left. A coordinate system maps each grid cell (r, c) to the point (c, -r) in the plane (so x increases rightward, y increases upward).

Compute the area enclosed by the polygon using the shoelace formula.

Input

The first line contains h and w, the height and width of the ASCII grid (1 ≤ h, w ≤ 200).

The next h lines each contain exactly w characters. The grid contains:

  • *: a vertex of the polygon
  • -: a horizontal edge
  • |: a vertical edge
  • /: a diagonal edge (connects bottom-left to top-right of a cell)
  • \: a diagonal edge (connects top-left to bottom-right of a cell)
  • .: empty space

How edges are drawn:

  • Every edge is exactly one character between its two vertices, so the vertices are two cells apart. With the edge character at row r, column c:
    • - joins the vertices at (r, c-1) and (r, c+1);
    • | joins (r-1, c) and (r+1, c);
    • / joins (r+1, c-1) and (r-1, c+1);
    • \ joins (r-1, c-1) and (r+1, c+1).
  • Every -, |, / and \ in the grid is an edge of the polygon, and every vertex has exactly two edges.
  • Three or more consecutive vertices may lie on a line (e.g. *-*-*).

The polygon is simple (non-self-intersecting) and vertices are connected in order by edges. The first vertex appears first in row-major order (top to bottom, left to right).

Output

Print the area of the polygon as a floating-point number with absolute or relative error at most 10^-6.

Notes

The shoelace formula computes the area of a polygon from its vertices (x₁, y₁), (x₂, y₂), ..., (xₙ, yₙ) as:

Area = |Σᵢ (xᵢ·yᵢ₊₁ - xᵢ₊₁·yᵢ)| / 2

where indices are modulo n. In the ASCII grid, each cell (r, c) corresponds to the point (c, -r) in the coordinate system.

Answers within 1e-06 absolute or relative error are accepted.

Example 1

Input

3 3
*-*
|.|
*-*

Output

4.0

Example 2

Input

3 3
*..
|\.
*-*

Output

2.0

Hints · reveal one at a time if you're stuck

Hint 1

Each edge character joins two vertices that lie two cells away, in the direction the character shows. Given a - at (r, c), which two cells are its endpoints? Think about what this means for how many edges each vertex has.

Hint 2

Build the graph of vertices from the edge characters, then walk it like a cycle starting from the first vertex. At each vertex, take the neighbour you did not just come from, and stop when you return to the start.

Hint 3

With the vertices in walking order, apply the shoelace formula from the statement using the coordinates (c, -r) of each vertex, and print the absolute value of half the sum.

report an issue Prefer your own editor? sooks prep 218 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.