Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Imagine that the user specifies with width and height of a grid, and two tiles i

ID: 3732903 • Letter: I

Question

Imagine that the user specifies with width and height of a grid, and two tiles in that grid. Find the shortest distance between the two tiles, where you are allowed only one right angle turn. For example, on a 7x10 grid,


the shortest distance between tiles 9 and 26 is 4. The shortest distance between tiles 63 and 69 is zero, and the shortest distance between tiles 68 and 69 is also zero.

You may use the following formulas in your solution as needed:

row = (tile - 1) // width

column = (tile - 1) % width

Template:

def getDistance(width, height, tile1, tile2):
    width = width
    height = height
    tile1 = tile1
    tile2 = tile2


    #YOUR CODE GOES HERE (indented)

    return "fixme"
    #END YOUR CODE

1 2 3 4 5 6 7 8 9 14 15 22 23 24 25 26 27 28 29 36 43 50 57 63 64 65 66 67 68 69 70

Explanation / Answer

def getDistance(width, height, tile1, tile2):
   width = width
   height = height
   tile1 = tile1
   tile2 = tile2
  
   row1 = (tile1-1)/width
   col1 = (tile1-1)%width
  
   row2 = (tile2-1)/width
   col2 = (tile2-1)%width
  
   if (abs(row1-row2) == 1 and abs(col1-col2) == 1) or (abs(row1-row2) == 0 and abs(col1-col2) == 1) or (abs(row1-row2) == 1 and abs(col1-col2) == 0):
       return 0
  
   return abs(row1-row2) + abs(col1-col2) - 1