The shortest path in the grid leetcode 5286

M * n to give you a grid, where each cell is not 0 (empty) is 1 (obstacle). Every step, you can be on the blank cell, down, left, right.

If you can eliminate most k obstacles, find the shortest path from the upper left corner (0, 0) to the lower right (m-1, n-1), and returns the number of steps required by the path. If no such path, it returns -1.

Problem-solving ideas is BFS, every encounter an obstacle, currently there is no chance to see over obstacles. The first time to write not take into account the status of each grid is not just a fact, because the number of obstacles to achieve through the current grid is different, so to add a dimension vis save

He went to the current grid, after a total of how many obstacles. Second, the number of states in the trellis are limited, at most n * m, note this condition, or the endless loop.

Last code is as follows:

class Solution {
public:
    struct T{
        int x,y;
        int step;
        int k;
    };
    queue<T>q;
    int dx[4]={-1,1,0,0};
    int dy[4]={0,0,1,-1};
    bool vis[41][41][41*41];
    int bfs(vector<vector<int>>& grid,int m,int n,int k)
    {
        memset(vis,0,sizeof(vis));
        T init;
        init.x=0;init.y=0;
        init.step=0;init.k=0;
        vis[0][0][0]=1;
        q.push(init);
        while(!q.empty())
        {
            T tmp=q.front();
            if(tmp.x==m-1&&tmp.y==n-1)
                return tmp.step;
            q.pop();
            for(int i=0;i<4;i++)
            {
                int xx=tmp.x+dx[i];
                int yy=tmp.y+dy[i];
                if(xx>=0&&xx<m&&yy>=0&&yy<n)
                {
                    if(grid[xx][yy]==1&&tmp.k+1<=k&&!vis[xx][yy][tmp.k+1]&&tmp.k+1<=n*m)
                    {
                        //cout<<"ww: "<<xx<<" "<<yy<<" "<<tmp.k+1<<endl;
                        vis[xx][yy][tmp.k+1]=1;
                        T tp;
                        tp.k=tmp.k+1;
                        tp.step=tmp.step+1;
                        tp.x=xx;
                        tp.y=yy;
                        q.push(tp);
                    }
                    else if(grid[xx][yy]==0&&tmp.k<=n*m&&!vis[xx][yy][tmp.k])
                    {
                        vis[xx][yy][tmp.k]=1;
                        T tp;
                        tp.k=tmp.k;
                        tp.step=tmp.step+1;
                        tp.x=xx;
                        tp.y=yy;
                        q.push(tp);
                    }
                }
            }
        }
        return -1;
    }
    int shortestPath(vector<vector<int>>& grid, int k) {
        int m=grid.size();
        int n=grid[0].size();
        return bfs(grid,m,n,k);
    }
};

Guess you like

Origin www.cnblogs.com/flightless/p/12044639.html