I finally found a simple approach to do this by divide-and-conquer.
Theory based-on: Add a line segment will split current area into two grids.
Based on above, the number should be quite straight forward, i.e. number_line_segments+1
.
To determine the edges of every grid, we further need to know which area is split when a new line segment is added.
Then, the problem is transformed to: how to determine a valid adding sequence (not unique) of all the line segments. Here, "valid"
means when adding a new line segment, it will split current area into two grids.
To determine a valid adding sequence of all the line segments, all I need to do is to determine the order for any two, which can be determined as follows:
order_for_two_line_segments(LineSeg LineSeg_A, LineSeg LineSeg_B)
{
if (one of LineSeg_A's end points is on LineSeg_B)
LineSeg_B should come before LineSeg_A;
else if (one of LineSeg_B's end points is on LineSeg_A)
LineSeg_A should come before LineSeg_B;
else // neither end points of them are on the other one
they can be in any order;
}
For example, in the following image (all lines are labelled as L1-L6
), L1
should come before L2
because one of L2
's end point is on L1
, without which L2
cannot form a valid split. And any order can be possible between L2
and L6
as neither end points of them are on the other one, which makes any one of them (without the other) can still form a valid split.
And a valid adding sequence can be L3 > L1 > L2 > L5 > L4 > L6
.
Edit: The above approach should also work for general cases where the grids can be any shape.