1

I was solving one question where we need to find the sum of Manhattan distances from a cell to all other given cells in a matrix. Now I am wondering why does BFS give Manhattan distance.

Question:

You are given an m x n grid grid of values 0, 1, or 2, where:

- each 0 marks an empty land that you can pass by freely,
- each 1 marks a building that you cannot pass through, and
- each 2 marks an obstacle that you cannot pass through.

You want to build a house on an empty land that reaches all buildings in the shortest total travel distance. You can only move up, down, left, and right.
Return the shortest travel distance for such a house. If it is not possible to build such a house according to the above rules, return -1.
The total travel distance is the sum of the distances between the houses of the friends and the meeting point.

The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.

Example:

Input: grid = [
  [1,0,2,0,1],
  [0,0,0,0,0],
  [0,0,1,0,0]
]

Output: 7
Explanation: Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2).
The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal.
So return 7.
Olivier
  • 13,283
  • 1
  • 8
  • 24
Kaneki
  • 65
  • 5
  • 2
    Your graph is not weighted. Each edge has the same weight of `1`, basically. BFS is legit a shortest-path algorithm on unweighted graphs. You will not be able to apply it anymore if your graph has weighted edges. Manhatten-distance is a metric used on "grids". Not on arbitrary graphs. BFS can be used on any graph. So you are hitting a special edge case here where those things collapse and mean the same. – Zabuzard Aug 02 '21 at 16:22
  • In short: Manhattan is a grid. – trincot Aug 02 '21 at 17:08
  • 1
    *"You can only move up, down, left, and right."* If you allowed diagonal movement, then the BFS would not be using Manhattan distance. Up, down, left, right is the definition of Manhattan distance. – user3386109 Aug 02 '21 at 18:10

0 Answers0