from collections import deque
# Function to find the shortest path from your location to any food cell
def findShortestPathToFood(grid):
# Define the four possible directions to move in the grid
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
# Get the size of the grid
numRows, numCols = len(grid), len(grid[0])
# Initialize a queue to keep track of cells to visit
Q = deque() # (value, distance, x, y)
# Find your location in the grid and add it to the queue
for row in range(numRows):
for col in range(numCols):
if grid[row][col] == '*':
Q.append((1, 0, row, col))
# Initialize the result to -1 (no path found)
shortestPathLength = -1
# Create a visited matrix to keep track of visited cells
visited = [[0] * numCols for _ in range(numRows)]
# Start BFS
while Q:
currentCell = Q.popleft()
# If we have reached a food cell, update the shortest path length and break
if currentCell[0] == 2:
shortestPathLength = currentCell[1]
break
# Visit all adjacent cells
for direction in directions:
newRow, newCol = direction[0] + currentCell[2], direction[1] + currentCell[3]
# If the new cell is within the grid, not an obstacle, and not visited
if 0 <= newRow < numRows and 0 <= newCol < numCols and (grid[newRow][newCol] == 'O' or grid[newRow][newCol] == '#') and not visited[newRow][newCol]:
# Mark the new cell as visited
visited[newRow][newCol] = 1
# If the new cell is a food cell, add it to the queue with a priority of 2
if grid[newRow][newCol] == '#':
Q.append((2, currentCell[1] + 1, newRow, newCol))
# If the new cell is a free space, add it to the queue with a priority of 3
else:
Q.append((3, currentCell[1] + 1, newRow, newCol))
# Return the length of the shortest path to reach any food cell, or -1 if no path exists
return shortestPathLength
# Driver code
if __name__ == "__main__":
grid = [
['X', 'X', 'X', 'X', 'X', 'X'],
['X', '*', 'O', 'O', 'O', 'X'],
['X', 'O', 'O', '#', 'O', 'X'],
['X', 'X', 'X', 'X', 'X', 'X']
]
print(findShortestPathToFood(grid))