Extended Manhattan Distance

Interview

Time limit1sMemory limit128 MB

Summary
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 Δx+Δy\Delta x + \Delta y. 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 AA to point BB, 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 11 unit apart. Two points AA and BB with integer coordinates are also given. Compute the length of the shortest path from AA to BB, 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:

xLyLxUyUxAyAxByBx_L \quad y_L \quad x_U \quad y_U \quad x_A \quad y_A \quad x_B \quad y_B

Here L=(xL,yL)L = (x_L, y_L) and U=(xU,yU)U = (x_U, y_U) are the lower-left and upper-right corners of the city grid, and A=(xA,yA)A = (x_A, y_A) and B=(xB,yB)B = (x_B, y_B) are the two points to travel between.

Every integer is in the range −1000-1000 to 10001000 inclusive, with xL<xUx_L < x_U and yL<yUy_L < y_U. 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 AA to BB, rounded to exactly three decimal places.

Examples1

  1. Example 1

    Input
    0 0 4 4 -1 0 5 3
    0 0 4 4 2 2 5 3
    0 0 0 0 0 0 0 0
    
    Expected output
    7.650
    3.414