Total Distance to Visit City Blocks in Python

PythonServer Side ProgrammingProgramming

Suppose we have a matrix of unique strings representing the city blocks, and another list of strings containing blocks to visit. If we are at block matrix[0][0], then find the total Manhattan distance required to visit every block in order.

So, if the input is like


Block = [H,B,C]

Then the output will be 6 as "h" is 2 blocks bottom(south) and 1 block right(east), "b" is 2 blocks up(north), "c" is 1 block right(east).

To solve this, we will follow these steps −

  • coords := a map with key 'start' and value (0, 0)
  • for each row in mat, do
    • for each col in mat, do
      • insert (row,col) into coords[mat[row, col]]
  • dist := 0
  • update blocks by adding 'start' at the beginning
  • for i in range 0 to size of blocks -1, do
    • c1 := coords[blocks[i]]
    • c2 := coords[blocks[i+1]]
    • d := |c1[0]-c2[0]| + |c1[1]-c2[1]|
    • dist := dist + d
  • return dist

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, mat, blocks):
      coords = {'start': (0,0)}
      for row in range(len(mat)):
         for col in range(len(mat[row])):
            coords[mat[row][col]] = (row,col)
      dist = 0
      blocks = ['start']+blocks
      for i in range(len(blocks)-1):
         c1 = coords[blocks[i]]
         c2 = coords[blocks[i+1]]
         d = abs(c1[0]-c2[0]) + abs(c1[1]-c2[1])
         dist += d
      return dist
ob = Solution()
inp = [["q", "b", "c"],
["d", "e", "z"],
["g", "h", "i"]]
blk = ["h", "b", "c"]
print(ob.solve(inp, blk))


[["q", "b", "c"],["d", "e", "z"],["g", "h", "i"]]


Updated on 22-Sep-2020 10:58:41