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
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