Problem statement

https://binarysearch.com/problems/City-Blocks/

Solution

Create hash table which maps names to coordinates. Then traverse blocks.

Complexity

It is O(mn) for time and space.

Code

class Solution:
    def solve(self, M, blocks):
        m, n = len(M), len(M[0])
        d = {}
        for i in range(m):
            for j in range(n):
                d[M[i][j]] = (i, j)

        ans = 0
        for x, y in zip(blocks, [M[0][0]] + blocks):
            ans += abs(d[x][0] - d[y][0]) + abs(d[x][1] - d[y][1])

        return ans