VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-labyrinth/

⇱ CSES Solutions – Labyrinth - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions – Labyrinth

Last Updated : 23 Jul, 2025

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:

  • Read the dimensions of the grid and initialize the grid with the static input.
  • Find the starting and ending positions in the grid.
  • Implement a BFS (Breadth-First Search) algorithm to the find the shortest path from the starting point to the ending point.
  • If the ending point is reachable reconstruct the path using a parent array to the store the direction of the movement at each cell.
  • Output "YES" followed by the minimum number of the steps required to reach the ending point and sequence of movements to the reach there. If the ending point is not reachable output "NO".

Below is the implementation of the algorithm:


Output
YES
9
LDDRRRRRU

Time Complexity: O(n*m)
Auxiliary Space: O(n*m)

Comment
Article Tags:
Article Tags: