← 返回 databricks 的题目列表Find Shortest Path in a Grid
类型:online_judge
Given a 2D city grid containing a start point (S), a destination point (D), and roadblocks (X), devise an algorithm to find the shortest path from the start to the destination. You can move in four cardinal directions (up, down, left, right). Cells marked with roadblocks are impassable. If the destination cannot be reached, return -1.
Input
A 2D character array representing the city grid. Valid characters include 'S' (start), 'D' (destination), 'X' (roadblock), and '.' (passage).
Output
The length of the shortest path. Return -1 if a path does not exist.
Test cases
Input: [['S', '.', 'X'], ['.', '.', '.'], ['.', 'X', 'D']], Output: 4
Input: [['S', 'X'], ['X', 'D']], Output: -1
Input: [['S', '.', 'D']], Output: 2
Input: [['S', '.', '.', 'X', 'D']], Output: 4
Input: [['S', 'X', '.', '.', 'D']], Output: 4
Constraints
The grid size does not exceed 100x100.
Example
Input
[['S', '.', 'X'], ['.', '.', '.'], ['.', 'X', 'D']]