Fold-up patterns for solids like cubes or octahedrons can be found in many books on geometry, but without actually folding them it is hard to tell whether the constructions really work. In this problem, we will consider a special class of such patterns.
Given a fold-up pattern built from unit squares in the plane, together with a description along what edges it should be folded in what direction, decide whether it will result in a closed surface of a solid in three dimensions. If it does, find the volume of the solid.
More precisely, the pattern consists of a connected set of unit squares in the plane. For any edge between connected sides you are told whether to fold forward, backward (always at a right angle), or not at all along that edge. If an edge between two adjacent squares in the pattern is not mentioned in the input, you may assume that the squares are not connected and can be ripped apart when folding. However, connected edges must always be folded according to the description.
For our purposes a closed surface is one where every square in the pattern separates the inside from the outside. When folded, the squares of the pattern lie on a rectangular, 3-dimensional grid, and each separates a cell (cubes of side length one unit) on the inside from one on the outside. For every cell it must be clear whether it is inside or outside. The following sketch illustrates this rule in two dimensions.
Note that even the second pattern above satisfies our definition of a closed surface, but the interior is not connected.
Two different squares may not occupy exactly the same position in space, though they may (and will for a closed surface) touch at edges and vertices. Make sure that the pattern does not interpenetrate itself through connected edges. Apart from that, do not worry about the process of folding, e.g. what edges are folded first or whether part of the structure is in the way for the rest.