1

Assuming two points, (x1, y1) and (x2, y2), how do we find the minimum number of steps required to reach (x2, y2) from (x1, y1), assuming we can move vertically, horizontally or diagonally?

I have the following code that produces this result, but does so slowly. I'd like this result in O(1). How can I do this, preferably without using libraries?

def _dist(x1, y1, x2, y2):
    steps = 0
    while (x1, y1) != (x2, y2):
        dX, dY = calculate_delta(x1, y1, x2, y2)
        (x1, y1) = (x1 + dX, y1 + dY)
        steps += 1
    return steps


def calculate_delta(s_i, s_j, e_i, e_j):
    i = 0 if s_i == e_i else -1 if e_i < s_i else 1
    j = 0 if s_j == e_j else -1 if e_j < s_j else 1
    return i, j
5
  • You can't do this in constant time, unless you have precomputed routes stored in a table somewhere (or if the grid size is fixed). Constant time doesn't mean "fast", it means "independent of the input size". Commented Jan 8, 2022 at 14:49
  • In your code however it looks like a diagonal step is counted as a horizontal/vertical step, is it right? Commented Jan 8, 2022 at 14:49
  • yes you could move from (2, 2) to (1, 1) in a single diagonal step Commented Jan 8, 2022 at 14:54
  • I think I'm assuming an incomplete graph. To confirm, you can always move to any adjacent point (with integer coordinates)? Commented Jan 8, 2022 at 15:17
  • no, the points are all contained in a finite grid, such as a chessboard Commented Jan 9, 2022 at 11:17

4 Answers 4

4

Assuming he could move diagonally the answer is:

def _dist(x1, y1, x2, y2):
    return max(abs(x1 - x2),abs(y1 - y2))

That's because he would do diagonally as many steps as there are units on the shortest axis plus as many steps as the difference in length between the axes: min + max - min = max

Sign up to request clarification or add additional context in comments.

Comments

2

The min steps is just the greatest difference in a single axis

def dist(x1, y1, x2, y2):
    return max(abs(x1 - x2), abs(y1 - y2))

Comments

1

The answer is simple use math function, it will take O(1):

def _dist(x1, y1, x2, y2):
    return max(abs(x1 - x2),abs(y1 - y2))

3 Comments

This assumes you only move horizontally or vertically, not diagonally.
Hi there, for future reference, please do not do as you have done (delete your comment because it was initially incorrect, then subsequently edit and re-publish with the accepted solution, leading to a confusing scenario for readers).
Yeah , Sorry I won't do it again
0

You could do like this:

def _dist(x1, y1, x2, y2):
    return max(abs(x1-x2), abs(y1-y2))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.