Modified Dijkstra Algorithm | Beats 96%
Code
\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    int minTimeToReach(vector<vector<int>>& grid) {\n        int n=grid.size(),m=grid[0].size();\n        priority_queue<pair<int,pair<bool,pair<int,int>>>,vector<pair<int,pair<bool,pair<int,int>>>>,greater<pair<int,pair<bool,pair<int,int>>>>>pq;\n        vector<vector<bool>>vis(n,vector<bool>(m,false));\n        //false =1 true=2\n        pq.push({0,{false,{0,0}}});\n        vis[0][0]=true;\n        vector<int>drow={-1,0,1,0},dcol={0,1,0,-1};\n        while(pq.empty()==false){\n            int time=pq.top().first;\n            bool mode=pq.top().second.first;\n            int row=pq.top().second.second.first;\n            int col=pq.top().second.second.second;\n            if(row==n-1 && col==m-1) return time;\n            pq.pop();\n            for(int i=0; i<4; i++){\n                int nrow=row+drow[i],ncol=col+dcol[i];\n                if(nrow>=0 && nrow<n && ncol>=0 && ncol<m && vis[nrow][ncol]==false){\n                    if(grid[nrow][ncol]<=time){\n                        pq.push({mode==false?time+1:time+2,{!mode,{nrow,ncol}}});\n                        vis[nrow][ncol]=true;\n                    }\n                    else{\n                        pq.push({mode==false?grid[nrow][ncol]+1:grid[nrow][ncol]+2,{!mode,{nrow,ncol}}});\n                        vis[nrow][ncol]=true;\n                    }\n                }\n            }\n        }\n        return -1;\n    }\n};\n```
['Array', 'Graph', 'Heap (Priority Queue)', 'Matrix', 'Shortest Path', 'C++']