Minimum Grid Manhattan Distance Between Target Characters
Trees & GraphsAuto-graded · 26 test casesLast updated
Find the minimum Manhattan distance between any pair of target characters in a 2D character grid.
Given a 2D grid represented as a list of strings, where each character is either 'X', 'Y', or 'O', calculate the minimum Manhattan distance between any cell containing 'X' and any cell containing 'Y'.
The Manhattan distance between two cells $(r_1, c_1)$ and $(r_2, c_2)$ is defined as: $$\text{dist} = |r_1 - r_2| + |c_1 - c_2|$$
If the grid does not contain at least one 'X' and at least one 'Y', return -1.
Constraints
- $1 \le \text{len}(grid) \le 1000$
- $1 \le \text{len}(grid[i]) \le 1000$ for all valid $i$
- All rows in $grid$ have equal length.
- Total number of cells $R \times C \le 10^6$.
- Every character in $grid$ is one of
'X','Y', or'O'.
Examples
Example 1
Input: min_xy_distance(['XOXOXXOOYOXO'])
Output: 2
Example 2
Input: min_xy_distance(['OXOOX', 'OOOOO', 'YOOOO'])
Output: 3
Example 3
Input: min_xy_distance(['XOX', 'OOO'])
Output: -1
Hints
Hint 1
Check if both 'X' and 'Y' exist in the grid first; if either is missing, return -1.
Hint 2
Comparing all pairs of 'X' and 'Y' can be up to O((R*C)^2), which is too slow. Can you process all 'X' cells simultaneously?
Hint 3
A multi-source Breadth-First Search (BFS) starting from all 'X' locations can compute the shortest distance to every cell in linear time O(R*C).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A naive pairwise comparison between every 'X' cell and every 'Y' cell takes $O(K_X \times K_Y)$ time, where $K_X$ and $K_Y$ are the counts of 'X' and 'Y' cells respectively. In the worst case, this requires $O((R \times C)^2)$ operations, which exceeds time limits for grids up to $10^6$ cells.
We can achieve optimal $O(R \times C)$ time using Multi-Source Breadth-First Search (BFS):
- Initialization: Scan the grid to locate all
'X'cells and check for the presence of at least one'Y'. If there are no'X'cells or no'Y'cells, immediately return-1. - Multi-Source Queue: Enqueue all positions of
'X'cells with a distance of0. Mark these initial cells as visited. - Level-by-Level Expansion: Perform a standard BFS. At each step, dequeue the current position $(r, c)$ and its distance $d$:
- If the current cell contains
'Y', the first time we encounter any'Y'gives the global minimum Manhattan distance because BFS visits cells in increasing order of distance. Return $d$. - Otherwise, explore its four orthogonal neighbors $(r \pm 1, c)$ and $(r, c \pm 1)$. If a neighbor is valid and unvisited, mark it as visited and enqueue it with distance $d + 1$.
- If the current cell contains
Correctness
In an unweighted grid with standard 4-directional moves, the shortest path distance in grid steps is identical to the Manhattan distance $|r_1 - r_2| + |c_1 - c_2|$. Initializing the queue with all 'X' cells simultaneously computes the distance from the nearest 'X' to every cell in increasing order. The first 'Y' reached guarantees the minimum distance.
Complexity
- Time Complexity: $O(R \times C)$, as every cell is pushed into the queue and visited at most once.
- Space Complexity: $O(R \times C)$ to maintain the
visitedgrid matrix and the BFS queue.
from collections import deque
from typing import List
def min_xy_distance(grid: List[str]) -> int:
R = len(grid)
C = len(grid[0])
queue = deque()
has_y = False
for r in range(R):
for c in range(C):
ch = grid[r][c]
if ch == 'X':
queue.append((r, c, 0))
elif ch == 'Y':
has_y = True
if not queue or not has_y:
return -1
visited = [[False] * C for _ in range(R)]
for r, c, _ in queue:
visited[r][c] = True
while queue:
r, c, d = queue.popleft()
if grid[r][c] == 'Y':
return d
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = r + dr, c + dc
if 0 <= nr < R and 0 <= nc < C and not visited[nr][nc]:
visited[nr][nc] = True
queue.append((nr, nc, d + 1))
return -1