Manhattan distance calculator

When calculating the distance between two points on a 2D plan/map we often calculate or measure the distance using straight line between these two points. Thought this “as the crow flies” distance can be very accurate it is not always relevant as there is not always a straight path between two points.

The perfect example to demonstrate this is to consider the street map of Manhattan which uses a grid-based layout: a mesh of horizontal and vertical roads crossing at a right angle.
taxicab-manhattan-grid-layout

Distance “as the crow flies”


The shortest distance between two points on a 2D grid is the distance using a straight line path between these two points.
taxicab-manhattan-grid-straight-path

On a 2D plan, using Pythagoras theorem we can calculate the distance between two points A and B as follows:
taxicab-manhattan-grid-straight-distance

Manhattan Distance (aka taxicab Distance)


The Manhattan distance (aka taxicab distance) is a measure of the distance between two points on a 2D plan when the path between these two points has to follow the grid layout. It is based on the idea that a taxi will have to stay on the road and will not be able to drive through buildings! The following paths all have the same taxicab distance:
taxicab-manhattan-grid-layout-paths

The taxicab distance between two points is measured along the axes at right angles.
taxicab-manhattan-grid-taxicab-distance
Note that the taxicab distance will always be greater or equal to the straight line distance.

Python Implementation


Check the following code to see how the calculation for the straight line distance and the taxicab distance can be implemented in Python.

Did you like this challenge?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 9

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: