# Total Distance to Visit City Blocks in Python

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, then find the total Manhattan distance required to visit every block in order.

So, if the input is like

 Q B C D E Z G G i

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-c2| + |c1-c2|
• dist := dist + d
• return dist

Let us see the following implementation to get better understanding −

## Example

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-c2) + abs(c1-c2)
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))

## Input

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

## Output

6