Shortest Service Path
At Urban Company, efficient service delivery is paramount. Our service technicians navigate various locations to reach customers. To optimize their routes and ensure timely service, we need to calculate the quickest way to a customer's location, especially when some areas are temporarily inaccessible due to maintenance or other reasons. This problem focuses on finding the minimum number of steps a technician needs to take to reach a customer.
You are tasked with implementing a function that calculates the minimum number of moves (steps) required for a service technician to travel from their starting point ('S') to a customer's service location ('T') within a given grid. The technician can move horizontally or vertically (up, down, left, right) to adjacent cells. They cannot move into blocked cells ('X') or outside the grid boundaries.
Your function should:
The function shortestServicePath takes one argument:
grid: A m x n 2D array of characters (string[][]) representing the service area.
The function should return an integer:
Examples
Example 1
Input:
grid = [["S", ".", "."], [".", "X", "."], [".", ".", "T"]]
Output:
4
Note:
Starting at (0,0), a possible shortest path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2), taking 4 moves.
Example 2
Input:
grid = [["S", "X", "."], ["X", "X", "."], [".", "X", "T"]]
Output:
-1
Note:
The starting point 'S' at (0,0) is completely blocked by 'X' cells, making 'T' at (2,2) unreachable.
Example 3
Input:
grid = [["S", "T", "."], [".", ".", "."]]
Output:
1
Note:
The target 'T' is directly adjacent to 'S'. One move from (0,0) to (0,1) reaches the target.
Example 4
Input:
grid = [["S", ".", "."], ["X", ".", "X"], [".", ".", "T"]]
Output:
5
Note:
Starting at (0,0), a possible shortest path is (0,0) -> (0,1) -> (0,2) -> (1,1) -> (2,1) -> (2,2), taking 5 moves, detouring around 'X' obstacles.
Constraints
1 <= m, n <= 100 (where m is the number of rows and n is the number of columns in the grid).grid[i][j] will be one of 'S', 'T', '.', or 'X'.Loading editor...