Perimeter
InterviewTime limit1sMemory limit128 MB
Given up to 10000 occupied cells in a 100 by 100 grid forming one connected region, find the outer perimeter, ignoring any holes.
- Level
Medium4 of 10
- Topics
- BFS, Graph, Simulation, Implementation
- Solved
- No attempts yet
Problem
Farmer John has arranged hay bales () in the middle of one of his fields. If we think of the field as a grid of square cells, each hay bale occupies exactly one of these cells (and, of course, no two hay bales occupy the same cell).
Farmer John notices that his hay bales form one large connected region: starting from any bale, one can reach any other bale by taking a series of steps north, south, east, or west onto directly adjacent bales. The connected region may, however, contain holes — empty regions that are completely surrounded by hay bales.
Please help Farmer John determine the perimeter of the region formed by his hay bales. Holes do not contribute to the perimeter.
Input
- Line 1: The number of hay bales, .
- Lines 2 to : Each line contains the location of a single hay bale, where and are integers in the range . Position is the lower-left cell of the field, and position is the upper-right cell.
Output
- Line 1: The perimeter of the connected region of hay bales.
Hint
Consider hay bales arranged into the following connected region:
XX
X XX
XXX
The perimeter of this region has length (for example, its left side contributes a length of ). Notice that the hole in the middle does not add to this total.