(This question is a variation of the LeetCode question 286. Walls and Gates. If you haven't completed that question yet, it is recommended to solve it first.)
The city map is represented by a 2D grid containing open roads, blocked roads, and DashMarts. As a city planner, your task is to help residents determine the shortest travel distance from their location to the nearest DashMart.
You are given a city grid where:
'D' represents a DashMart.' ' represents an open road you can travel on.'X' represents a blocked road you cannot pass through.You are also given a list of locations, where each location is a pair of [row, col] coordinates. For each given location, you must find the minimum number of steps required to reach any DashMart. You can only move one step at a time to an adjacent open road (up, down, left, or right).
If a location is a DashMart itself, the distance is 0. If a location is on a blocked cell or cannot reach any DashMart, its distance is -1.
Return an array of integers, where each element corresponds to the calculated shortest distance for each location in the input locations list, maintaining the original order.
Example 1:
Input: city = [['X', ' ', ' ', 'D', ' ', ' ', 'X', ' ', 'X'], ['X', ' ', 'X', 'X', ' ', ' ', ' ', ' ', 'X'], [' ', ' ', ' ', 'D', 'X', 'X', ' ', 'X', ' '], [' ', ' ', ' ', 'D', ' ', 'X', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', 'X', ' ', ' ', 'X'], [' ', ' ', ' ', ' ', 'X', ' ', ' ', 'X', 'X']], locations = [[2, 2], [4, 0], [0, 4], [2, 6]] Output: [1, 4, 1, 5] Explanation: For the first location at [2, 2], the nearest DashMart is at [2, 3]. The shortest path is one step to the right: (2, 2) -> (2, 3). Therefore, the distance is 1. The other distances are calculated similarly by finding the shortest path from each location to its closest DashMart.
Example 2:
Input: city = [[' ', 'D', ' '], [' ', 'X', ' '], [' ', ' ', ' ']], locations = [[0, 0], [2, 2], [0, 2]] Output: [1, 3, 1]
Example 3:
Input: city = [['D', ' ', ' ', 'D'], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], ['D', ' ', ' ', 'D']], locations = [[1, 1], [1, 2], [2, 1], [2, 2]] Output: [2, 2, 2, 2]
Constraints:
rows, cols ≤ 500city.length and locations.length ≤ city[i][j] is one of 'D', ' ', or 'X'.