Griddy Hobby
Time limit1sMemory limit128 MB
Starting from a boundary point, draw a 45-degree diagonal, then perpendicular segments until the path closes or stalls; count the minimal rectangles carved out.
- Level
Medium7 of 10
- Topics
- Simulation, Geometry, Implementation, Math
- Solved
- No attempts yet
Problem
During a long, dull weekly meeting, a professor started doodling on the grid printed in his notebook. He begins at a grid point that lies on the boundary of the grid (so is a corner of one or two grid cells). He draws the diagonal of one of those cells and keeps going in a straight line at 45° until he reaches a point on another edge of the grid. From he draws a new line perpendicular to , continuing until it hits yet another edge. He keeps adding lines this way, each perpendicular to the previous one, until he can no longer draw a new line — either because a perpendicular line would not begin with the diagonal of a cell, or because it would land on a line he has already drawn. At that moment he wonders how many minimal rectangles his drawing has carved out of the grid.

Given the grid dimensions and , the coordinates of the starting point on the boundary, and the direction of the first line, write a program that reports the number of minimal rectangles.
Input
The first line contains an integer , the number of test cases. Each test case is described by three lines.
The first line contains two integers and — the number of horizontal and vertical gridlines, respectively ().
The second line contains two integers and — the coordinates of the starting point (, ). The upper-left grid point is , with increasing to the right and increasing downward. always lies on an edge of the grid.
The third line contains a two-letter direction code for the first line:
DR— the first move goes down and to the right,DL— the first move goes down and to the left,UL— the first move goes up and to the left,UR— the first move goes up and to the right.
Output
For each test case, print a single line containing the number of minimal (non-overlapping) rectangles formed.