KatInterview

Shortest Path from Multiple Sources in a Grid

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsbfsgraph-traversalshortest-path

Last updated

Tests understanding of multi-source BFS to efficiently compute shortest distances from any of several starting points to many query locations.

You're working with a rectangular grid represented as a 2D array with m rows and n columns. Each cell contains one of three values:

  • 0 indicates a source location
  • -1 indicates an obstacle (cannot be traversed)
  • 2147483647 (2³¹ - 1) indicates an open space

Movement between cells is restricted to four directions (up, down, left, right), and each move has a cost of 1.

Given a list of query coordinates, where each query is a pair [row, col] representing an open space in the grid, determine the length of the shortest path from each query location to any source. If a query location cannot reach any source, return -1 for that query.

Implement a function that returns an array of integers, one for each query in the same order as the input queries.

Constraints:

  • 0 ≤ m, n ≤ 1000
  • 0 ≤ k ≤ 100000 (number of queries)
  • All query coordinates are guaranteed to be valid indices within the grid
  • All query coordinates point to open spaces (cells with value 2147483647)
  • Grid cells contain only the three specified values: 0, -1, or 2147483647

Examples

Example 1

Input: shortest_source_distances([[0, 2147483647, 2147483647], [-1, 2147483647, 0], [2147483647, 2147483647, -1]], [[0, 1], [0, 2], [1, 1], [2, 0]])

Output: [1, 1, 1, 3]

Example 2

Input: shortest_source_distances([[-1, 2147483647], [-1, 2147483647]], [[0, 1], [1, 1]])

Output: [-1, -1]

Example 3

Input: shortest_source_distances([[0, 2147483647, 2147483647], [2147483647, -1, 2147483647]], [[0, 1], [0, 2], [1, 0], [1, 2]])

Output: [1, 2, 1, 3]

Example 4

Input: shortest_source_distances([[0, 2147483647, -1, 2147483647], [2147483647, 2147483647, -1, 2147483647], [-1, -1, -1, 2147483647], [2147483647, 2147483647, 2147483647, 0]], [[0, 1], [1, 0], [1, 1], [3, 2]])

Output: [1, 1, 2, 1]

Hints

Hint 1

Instead of searching from each query toward sources, consider searching from sources toward all reachable cells.

Hint 2

Multi-source BFS can process all sources simultaneously by initializing the queue with all source locations at distance 0.

Hint 3

Precomputing distances to all cells allows you to answer each query in constant time.