Thursday, January 12, 2023

[LeetCode] Shortest Path in a Grid with Obstacles Elimination

Problem: You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.

Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.

Example:

Input: grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1
Output: 6
Explanation: 
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).

Input: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1
Output: -1
Explanation: We need to eliminate at least two obstacles to find such a walk.


Approach: This is again a BSF problem but here the next state/node is just not the neighbor cells but with that the number of obstacles removed is also part of next state so the edge is (x, y, number of obstacles removed).

That's all! 


Implementation in C#:

public class QueueData
{
    public int X {get; set;}
    public int Y {get; set;}
    public int Obstacles {get; set;}
    public QueueData(int x, int y, int obs)
    {
        this.X = x;
        this.Y = y;
        this.Obstacles = obs;
    }
}

public class Solution
{
    public int ShortestPath(int[][] grid, int k)
    {
        int rows = grid?.Length ?? 0;
        if(rows == 0)
        {
            return 0;
        }
        int cols = grid[0].Length;
        if (k == 0 && grid[0][0] == 1)
        {
            return -1;
        }
        bool[,,] visited = new bool[rows, cols, k + 1];
        Queue<QueueData> queue = new Queue<QueueData>();
        int obstacle = grid[0][0] == 1 ? 1 : 0;
        queue.Enqueue(new QueueData(0, 0, obstacle));
        visited[0, 0, obstacle] = true;
        int steps = 0;
        while(queue.Count > 0)
        {
            int size = queue.Count;
            for (int i = 0; i < size; ++i)
            {
                var queueData = queue.Dequeue();
                if (queueData.X == rows - 1 &&
                    queueData.Y == cols - 1)
                {
                    return steps;
                }

                this.AddValidNeighboursToQueue(
                                            grid,
                                            queue,
                                            queueData,
                                            visited,
                                            k);
            }
            ++steps;
        }
        return -1;
    }

    private void AddValidNeighboursToQueue(
                            int[][] grid,
                            Queue<QueueData> queue,
                            QueueData data,
                            bool[,,] visited,
                            int maxObstacles)
    {
        int x = data.X;
        int y = data.Y;
        int obstacles = data.Obstacles;
        if (this.IsValidCell(grid, x - 1, y))
        {
            this.AddCellToQueueIfPossible(grid,
                                        queue,
                                        x - 1,
                                        y,
                                        obstacles,
                                        maxObstacles,
                                        visited);
        }
        if (this.IsValidCell(grid, x + 1, y))
        {
            this.AddCellToQueueIfPossible(grid,
                                        queue,
                                        x + 1,
                                        y,
                                        obstacles,
                                        maxObstacles,
                                        visited);
        }
        if (this.IsValidCell(grid, x, y - 1))
        {
            this.AddCellToQueueIfPossible(grid,
                                        queue,
                                        x,
                                        y - 1,
                                        obstacles,
                                        maxObstacles,
                                        visited);
        }
        if (this.IsValidCell(grid, x, y + 1))
        {
            this.AddCellToQueueIfPossible(grid,
                                        queue,
                                        x,
                                        y + 1,
                                        obstacles,
                                        maxObstacles,
                                        visited);
        }
    }

    private void AddCellToQueueIfPossible(
                                int[][] grid,
                                Queue<QueueData> queue,
                                int x,
                                int y,
                                int obstacles,
                                int maxObstacles,
                                bool[,,] visited)
    {
        if (grid[x][y] == 1)
        {
            ++obstacles;
        }
        if (obstacles <= maxObstacles && !visited[x, y, obstacles])
        {
            visited[x, y, obstacles] = true;
            queue.Enqueue(new QueueData(x, y, obstacles));
        }
    }

    private bool IsValidCell(int[][] grid, int x, int y)
    {
        return x >= 0 &&
            x < grid.Length &&
            y >= 0 &&
            y < grid[0].Length;
    }
}

Complexity: O(n^2)

No comments:

Post a Comment