![]() |
VOOZH | about |
You are given a map of a labyrinth, and your task is to find a path from start to end. You can walk left, right, up and down.
The first input line has two integers n and m: the height and width of the map. Then there are lines of m characters describing the labyrinth. Each character is . (floor), # (wall), A (start), or B (end). There is exactly one A and one B in the input.
Examples:
Input: n = 5, m = 8, labyrinth = {"########", "#.A#...#", "#.##.#B#", "#......#", "########" }
Output:
YES
9
LDDRRRRRU
Explanation: The shortest path has 9 moves: Left, Down, Down, Right, Right, Right, Right, Right, Up.Input: n = 10, m = 10, labyrinth = {"##.A######", "#.##.##.##", "#####..###", ".#########", ".########.", "###.###.##", "#########.", "######.#.#", "###..###.#", "###.B#####"}
Output: NO
Approach:
To find the path from the start to end in the labyrinth we can use a breadth-first search (BFS) algorithm. We start BFS from the starting point ('A') and explore all possible directions (left, right, up, down) until we reach the end point ('B'). We keep track of the shortest path length and path itself during BFS traversal. Also, keep a track of the direction from which we have visited the current cell. For example: if we have visited the current cell by moving down from the cell above, then we store 'D' in steps[][].
Step-by-step algorithm:
Below is the implementation of the algorithm:
YES 9 LDDRRRRRU
Time Complexity: O(n*m)
Auxiliary Space: O(n*m)