Perimeter

Interview

Time limit1sMemory limit128 MB

Summary
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 NN hay bales (1≤N≤10,0001 \le N \le 10{,}000) in the middle of one of his fields. If we think of the field as a 100×100100 \times 100 grid of 1×11 \times 1 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, NN.
  • Lines 2 to N+1N+1: Each line contains the location (x,y)(x, y) of a single hay bale, where xx and yy are integers in the range 1…1001 \dots 100. Position (1,1)(1, 1) is the lower-left cell of the field, and position (100,100)(100, 100) 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 1414 (for example, its left side contributes a length of 33). Notice that the hole in the middle does not add to this total.

Examples1

  1. Example 1

    Input
    8
    5 3
    5 4
    8 4
    5 5
    6 3
    7 3
    7 4
    6 5
    
    Expected output
    14