KatInterview

Minimum Grid Manhattan Distance Between Target Characters

Trees & GraphsAuto-graded · 26 test cases
MediumAuto-gradedTrees & Graphsbfsmatrixdistance-transform

Last 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).