This question evaluates grid traversal and shortest-path competencies, specifically breadth-first search for finding minimum steps in a 2D maze, along with correct array traversal and output formatting for printing the maze.

You are given a 2D grid representing a maze. Each cell of the grid is one of:
'#'
– wall (cannot be passed)
'.'
– empty path (can be passed)
'S'
– start position (exactly one in the grid)
'E'
– exit position (exactly one in the grid)
You need to complete two related tasks.
You are given a function with the following conceptual behavior:
grid
of characters with
R
rows and
C
columns.
Requirements:
Example input grid (shown here as a matrix):
['#', '#', '#', '#']
['#', 'S', '.', '#']
['#', '.', 'E', '#']
['#', '#', '#', '#']
Expected output to stdout:
####
#S.#
#.E#
####
The existing implementation has a bug and prints the maze incorrectly (for example, transposed rows/columns, missing newlines, or extra spaces). Describe how you would implement or fix the printing logic to satisfy the above specification.
Assume constraints:
Implement a function with the following behavior:
'#'
). If there is no path, return -1.
More formally:
Example:
Using the previous 4×4 grid:
####
#S.#
#.E#
####
One valid shortest path is:
The shortest path length is 2, so the function should return 2.
You may be asked to implement this in stages (first only detect reachability, then return distance, then optionally reconstruct the actual path), but the final requirement is to return the shortest path length.
State the algorithm you would use (time and space complexity) and how you would implement it robustly for the given constraints.