function minStepsInMaze(maze):
rows = number of rows in maze
cols = number of columns in maze
# Find the coordinates of the start (S) and exit (E)
start = findCoordinates(maze, 'S')
exit = findCoordinates(maze, 'E')
# Direction vectors for moving up, down, left, right
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
# Queue for BFS that stores (x, y, steps) where steps is the count of moves taken
queue = Queue()
queue.enqueue((start[0], start[1], 0)) # Enqueue start with 0 steps
# Visited set to track visited cells and avoid cycles
visited = set()
visited.add((start[0], start[1]))
# BFS loop
while not queue.isEmpty():
(x, y, steps) = queue.dequeue()
# If we have reached the exit, return the number of steps taken
if (x, y) == exit:
return steps
# Explore neighbors
for direction in directions:
newX = x + direction[0]
newY = y + direction[1]
# Check if new coordinates are within bounds and path is open
if isValid(newX, newY, rows, cols) and maze[newX][newY] != '1' and (newX, newY) not in visited:
# Mark new cell as visited
visited.add((newX, newY))
# Enqueue new cell with incremented step count
queue.enqueue((newX, newY, steps + 1))
# If we exhaust the queue without finding the exit, return -1
return -1
# Helper function to check bounds
function isValid(x, y, rows, cols):
return 0 <= x < rows and 0 <= y < cols
# Helper function to locate the coordinates of a target (S or E) in the grid
function findCoordinates(maze, target):
for i in range(0, len(maze)):
for j in range(0, len(maze[0])):
if maze[i][j] == target:
return (i, j)