Question

I have the following implemented in Java:

  [1,1][1,2][1,3][1,4]
  [2,1][2,2][ B ][2,4]
  [ A ][3,2][3,3][3,4]

I want to be able to calculate the Minimum distance between [ A ] and [ B ], without moving diagonally, i have searched online, but I'm not really sure how to word what I'm looking for. so far i have been able to calculate the diagonal distance using:

dMin = Math.min(dMin, Math.abs((xDistance - yDistance)));

Could some one please give me an algorithm i could look for online? any help is appreciated. thanks for you time :)

Expected output is:

Distance = 3 //Not Distance = 2 (as it would be diagonally).
Was it helpful?

Solution

It's called Manhattan Distance and can easily be computed by:

distance = abs(ydistance) + abs(xdistance)

That is, the number of cells you must travel vertically, plus the number of cells you must travel horizontally, much like a taxi driving through a grid of city streets.

OTHER TIPS

You want the absolute difference between the x values of the points, plus the absolute difference between the y values of the points.

ie:

dMin = Math.abs(A.x - B.x) + Math.abs(A.y - B.y)

This is known as Manhattan Distance

You want the difference along the X axis plus the difference along the Y axis. Something like this:

int minDistance = Math.abs(A.x - B.x) + Math.abs(A.y - B.y);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top