Rectangle Coloring
InterviewTime limit1sMemory limit128 MB
Count the groups of overlapping rectangles where touching edges count as overlap and each group gets one color.
- Level
Easy3 of 10
- Topics
- Union-find, Geometry
- Solved
- No attempts yet
Problem
You are given axis-parallel rectangles on the plane. An axis-parallel rectangle is a rectangle whose edges are parallel to the -axis or the -axis. Determine the number of colors needed to paint the rectangles according to the following rules.
- Each rectangle is painted with exactly one color.
- Two intersecting rectangles must be painted the same color. Regarding a rectangle as the set of points including its boundary, two rectangles intersect if their intersection is non-empty.
- For rectangles and , if there exists a sequence such that and intersect for every , then and must have the same color; otherwise they must have different colors. For example, in the figure below rectangle must have the same color as , , , and a different color from , , , , .

In other words, rectangles connected through the intersection relation form one group, and each group is painted a single distinct color. Hence the number of colors needed equals the number of such groups (connected components).
Input
The input consists of test cases. The first line contains the number of test cases . The first line of each test case contains the number of rectangles (). Each of the next lines contains four positive integers , , , () describing one rectangle, where is the lower-left corner and is the upper-right corner. The four integers are separated by one or more spaces.
Output
For each test case, print the number of colors needed, one per line.