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
Program to find minimum distance that needs to be covered to meet all person in Python
This problem asks us to find the optimal meeting point in a 2D grid where people can gather with minimum total walking distance. We have a grid with walls (1), empty spaces (0), and people (2), and need to find the location that minimizes the sum of distances all people must travel.
Problem Setup
Given a 2D matrix with:
0 represents an empty cell
1 represents a wall
2 represents a person
A person can move in four directions (up, down, left, right). We need to find a non-wall cell that minimizes the total travel distance for all people.
Example Input
| 2 | 0 | 1 | 0 |
| 1 | 0 | 1 | 2 |
| 0 | 0 | 2 | 2 |
The output should be 7, as the optimal meeting point minimizes total walking distance.
Algorithm Approach
We use Breadth-First Search (BFS) to calculate the shortest distance from each person to every reachable cell, then find the cell with minimum total cost:
Find all person positions and initialize distance matrices
For each person, run BFS to calculate distances to all reachable cells
Sum distances for each cell and find the minimum
Implementation
from collections import deque
class Solution:
def solve(self, matrix):
if not matrix or not matrix[0]:
return 0
rows, cols = len(matrix), len(matrix[0])
people_positions = []
# Find all people positions
for i in range(rows):
for j in range(cols):
if matrix[i][j] == 2:
people_positions.append((i, j))
if not people_positions:
return 0
# Calculate distances from each person to all reachable cells
all_distances = []
for person_row, person_col in people_positions:
# Initialize distance matrix for this person
distances = [[float('inf')] * cols for _ in range(rows)]
distances[person_row][person_col] = 0
# BFS to find shortest distances
queue = deque([(person_row, person_col, 0)])
visited = set()
while queue:
row, col, dist = queue.popleft()
if (row, col) in visited:
continue
visited.add((row, col))
distances[row][col] = dist
# Check all four directions
for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
new_row, new_col = row + dr, col + dc
if (0 <= new_row < rows and
0 <= new_col < cols and
matrix[new_row][new_col] != 1 and
(new_row, new_col) not in visited):
queue.append((new_row, new_col, dist + 1))
all_distances.append(distances)
# Find the cell with minimum total distance
min_total = float('inf')
for i in range(rows):
for j in range(cols):
if matrix[i][j] != 1: # Not a wall
total_distance = sum(distances[i][j] for distances in all_distances)
min_total = min(min_total, total_distance)
return min_total
# Test the solution
ob = Solution()
matrix = [
[2, 0, 1, 0],
[1, 0, 1, 2],
[0, 0, 2, 2]
]
result = ob.solve(matrix)
print(f"Minimum total distance: {result}")
Minimum total distance: 7
How It Works
The algorithm works in three main phases:
Person Detection: Scan the matrix to find all cells containing people (value 2)
Distance Calculation: For each person, use BFS to calculate the shortest distance to every reachable cell, avoiding walls
Optimal Point Finding: For each non-wall cell, sum the distances from all people and track the minimum
Time and Space Complexity
The time complexity is O(P × M × N) where P is the number of people, M is rows, and N is columns. Space complexity is O(P × M × N) for storing distance matrices.
Conclusion
This BFS-based approach efficiently finds the optimal meeting point by calculating shortest paths from each person to all reachable locations. The solution handles walls and ensures people can only move through valid cells to reach the meeting point.
