Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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[0][0], then find the total Manhattan distance required to visit every block in order.
The Manhattan distance between two points (x1, y1) and (x2, y2) is calculated as |x1 - x2| + |y1 - y2|.
Example Problem
Consider this city block matrix ?
| Q | B | C |
| D | E | Z |
| G | H | I |
Blocks to visit: ["H", "B", "C"]
Starting from position (0, 0), we need to visit:
-
H at position
(2, 1)? Distance:|0-2| + |0-1| = 3 -
B at position
(0, 1)? Distance:|2-0| + |1-1| = 2 -
C at position
(0, 2)? Distance:|0-0| + |1-2| = 1
Total distance: 3 + 2 + 1 = 6
Algorithm Steps
- Create a coordinate map with the starting position
(0, 0) - Map each block in the matrix to its coordinates
- Calculate Manhattan distance between consecutive positions
- Sum all distances to get the total
Implementation
class Solution:
def solve(self, matrix, blocks):
# Create coordinate mapping with starting position
coords = {'start': (0, 0)}
# Map each block to its position in the matrix
for row in range(len(matrix)):
for col in range(len(matrix[row])):
coords[matrix[row][col]] = (row, col)
# Calculate total distance
total_distance = 0
blocks = ['start'] + blocks
for i in range(len(blocks) - 1):
c1 = coords[blocks[i]]
c2 = coords[blocks[i + 1]]
# Manhattan distance formula
distance = abs(c1[0] - c2[0]) + abs(c1[1] - c2[1])
total_distance += distance
return total_distance
# Test the solution
solution = Solution()
city_matrix = [["q", "b", "c"],
["d", "e", "z"],
["g", "h", "i"]]
blocks_to_visit = ["h", "b", "c"]
result = solution.solve(city_matrix, blocks_to_visit)
print(f"Total Manhattan distance: {result}")
Total Manhattan distance: 6
How It Works
The algorithm first creates a mapping of each block to its coordinates. Then it calculates the Manhattan distance between each consecutive pair of blocks in the visiting order, starting from the initial position (0, 0).
Time Complexity
- Time Complexity: O(m × n + k), where m×n is the matrix size and k is the number of blocks to visit
- Space Complexity: O(m × n) for storing the coordinate mapping
Conclusion
This solution efficiently calculates the total Manhattan distance by mapping block positions and summing distances between consecutive visits. The approach works well for any matrix size and visiting sequence.
