Labyrinth

You are given a 2D grid representing a labyrinth. The grid contains the following characters:

  • . represents a floor you can walk on.
  • # represents a wall you cannot pass through.
  • A represents your starting position.
  • B represents your target destination.

You can move up, down, left, or right to any adjacent floor cell. Find the shortest path from A to B.

Return a string consisting of the characters 'U' (Up), 'D' (Down), 'L' (Left), and 'R' (Right) representing the sequence of moves for the shortest path.

  • If there are multiple shortest paths, you may return any of them.
  • If it is impossible to reach B from A, return an empty string "".

Example 1:

Input: grid = [

['A', '.', '.', '.'],

['#', '#', '#', '#'],

['.', '.', '.', 'B'] ]

Output: ""

Explanation:

A solid wall of '#' completely separates 'A' from 'B'. It is impossible to reach the destination.

Example 2:

Input: grid = [ ['A', 'B'] ]

Output: "R"

Explanation:

The destination is immediately to the right of the start, so one step Right is the shortest path.

Now Your Turn!

Pick the correct output for the given input

Input: grid = [['A', '.', 'B']]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= grid.length <= 1000
  • 1 <= grid[i].length <= 1000
  • grid.length * grid[i].length >= 2
  • grid[i][j] is either '.', '#', 'A', or 'B'.
  • There is exactly one 'A' and exactly one 'B' in the grid.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
string shortestPath(vector<vector<char>>& grid) {
// Write your code here
}
};
Test Case

Input:

Grid