Help with a project

Take a step back from the code aspect for a second and visualize your problem, which is basically this:

      1   2   3   4   5 

  1   +---+---+---+---+
      |   |   |   |   |
  2   +---A---+---+---+
      |   |   |   |   |
  3   +---+---+---+---+
      |   |   |   |   |
  4   +---+---+---+---+
      |   |   |   |   |
  5   +---+---+---B---+

Imagine this is your grid, and A and B are your "tiles". Math aside, you assume you already know their rows and columns, indicating their positions: in this case, A is at (row 2, column 2), and B is at (row 5, column 4).

Now then, the rule says you are only allowed 1 right angle turn. This means you don't need to do some fancy extra turns to get from A, and there are only two possible paths to take: either going to the right of A to reach B, or going down from A to reach B (or the appropriate reverse directions if you're going from B to A).

This is your basic path, assuming you go to the right of A (using > and V for direction):

      1   2   3   4   5 

  1   +---+---+---+---+
      |   |   |   |   |
  2   +---A>>>>>>>\---+
      |   |   |   V   |
  3   +---+---+---V---+
      |   |   |   V   |
  4   +---+---+---V---+
      |   |   |   V   |
  5   +---+---+---B---+

In this scenario, we travel to the right by 2 columns, then travel down by 3 rows. The distance traveled is essentially (2 + 3) = 5, which is the answer. Since this would be the same answer no matter which path we took from A to B, we don't need to test other paths.

Now, let's start to simplify this answer to a set of rules. Since you know which columns A and B are in, you can get the distance with simple subtraction of the columns. Same applies to the rows. You then add these numbers together.

So:

(B's column - A's column) + (B's row - A's row) = distance

Suppose that we reversed this, going from B to A. We'd end up with a negative distance, which doesn't make sense. We can account for this using absolute value:

4 - 1 = 3
1 - 4 = -3
absolute value of either answer = 3

Python has a built-in function, abs(), to give absolute value. So:

distance = abs(b_column - a_column) + abs(b_row - a_row)

And that should be your answer. Give it a try and see what you come up with.

/r/learnpython Thread