Extended Manhattan Distance
InterviewTime limit1sMemory limit128 MB
Given an axis-aligned city grid and two integer points, find the shortest path length when travel inside the grid is restricted to axis-parallel streets and travel outside is free in any direction.
- Level
Medium6 of 10
- Topics
- Geometry, Math, Implementation, Brute force
- Solved
- No attempts yet
Problem

The streets of Manhattan form a grid. When the grid lines are parallel to the x- and y-axes, the distance you must walk or drive from one point to another — moving only along the streets, never cutting through buildings — equals . This is the Manhattan distance.
Now suppose the land outside the city grid is completely flat, with no obstacles, so you may move freely in any direction there. We want to travel from point to point , where each point may lie inside the grid, on it, or outside it. Outside the city the shortest route is not necessarily the Manhattan distance: if both points lie on the grid it is the Manhattan distance, but if, for example, both lie north of the grid, the shortest route is the straight-line (Euclidean) distance. Other configurations can be more involved.
Two opposite corners of the city grid are given. The grid lines are parallel to the coordinate axes, and consecutive grid lines (horizontal or vertical) are unit apart. Two points and with integer coordinates are also given. Compute the length of the shortest path from to , given that inside the city grid you may move only along the grid lines (the streets).
Input
The input consists of several datasets. Each dataset is a single line with eight integers:
Here and are the lower-left and upper-right corners of the city grid, and and are the two points to travel between.
Every integer is in the range to inclusive, with and . The input ends with a line containing eight zeros, which is not processed.
Output
For each dataset, print one line containing the length of the shortest path from to , rounded to exactly three decimal places.