## Similar Problems

Similar Problems not available

# Mice And Cheese - Leetcode Solution

## Companies:

LeetCode: Mice And Cheese Leetcode Solution

Difficulty: Medium

Topics: greedy sorting heap-priority-queue array

The Mice and Cheese problem on LeetCode is a classic dynamic programming problem. The problem statement can be described as follow:

There is a room with a maze-like structure, denoted by a 2D grid of size n x m. Each cell in the grid is either blocked or unblocked. A mouse starts from cell (0, 0) and wants to reach the cell (n-1, m-1) which has a piece of cheese.

The mouse can move in four directions (up, down, left, right) and can only move to an unblocked cell. The mouse cannot move diagonally.

The objective is to find the shortest distance that the mouse needs to travel to reach the cell (n-1, m-1).

To solve this problem, we can use a dynamic programming approach. We create a 2D table of size n x m that will store the minimum distance from the mouse to each cell. We initialize all the cells in the table to infinity except for the starting cell which will have a distance of 0.

We then start exploring the maze starting from cell (0, 0). We use Breadth First Search (BFS) algorithm to explore all the unblocked cells in the maze. For each unblocked cell that we explore, we update the distance in the table if the new distance is shorter than the current distance.

Once we have explored all the unblocked cells in the maze, the final distance to the cell (n-1, m-1) will be stored in the table at cell (n-1, m-1). If the distance is still infinity, it means that there is no way for the mouse to reach the cheese.

Below is the Python implementation of the solution:

```
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
# check if the starting and ending cells are blocked
if grid[0][0] == 1 or grid[n-1][m-1] == 1:
return -1
# initialization
dp = [[float('inf') for j in range(m)] for i in range(n)]
dp[0][0] = 0
queue = [(0, 0)]
# BFS
while queue:
x, y = queue.pop(0)
for i, j in [(0, 1), (0, -1), (1, 0), (-1, 0), (-1, -1), (1, -1), (1, 1), (-1, 1)]:
new_x, new_y = x + i, y + j
# check if the new cell is within the maze
if new_x >= 0 and new_x < n and new_y >= 0 and new_y < m:
# check if the new cell is unblocked
if grid[new_x][new_y] == 0:
# update the distance to the new cell
if dp[new_x][new_y] > dp[x][y] + 1:
dp[new_x][new_y] = dp[x][y] + 1
queue.append((new_x, new_y))
# return the final distance to the ending cell
return dp[n-1][m-1] if dp[n-1][m-1] != float('inf') else -1
```

Time Complexity: O(n*m)

Space Complexity: O(n*m)

## Mice And Cheese Solution Code

`1`