Easy beat 100% runtime and memory at the same time with C++
Intuition\nWe can transfer the question to an easy shortest path problem.\nEasy point minimum time required will be min(adjacent time, grid.time+1/0).\n\n# Appr
# Intuition\nWe can transfer the question to an easy shortest path problem.\nEasy point minimum time required will be **min(adjacent time, grid.time+1/0)**.\n\n# Approach\nEarly return when grid[0][1] and grid[1][0] bigger than 1 at the same time. It is the only situation with no solution.\nFirst, put the top-left cell into the priority_queue.\nEach time pick the cell with minimum cost (cost_i) in priority_queue with move one distance.\nTwo situations after one moving:\n1. If the adjacent cell required time smaller than cost_i + 1, new cost will be cost_i + 1;\n2. If the required time bigger than cost_i + 1, the new cost will be grid[new x][new y] + 1/0. \nBecause we can keep going back and forth between two points until required time is reached. \n(Eg. cost_i +1 +2 +2.... until >= grid[new x][new y])\n\n**Based on the pq priority and the same edge cost, We can guarantee when we first time touch the cell, it gets mimimum cost**. \nFinally, we can get the minimum required time when we touch the cell[m-1][n-1].\n\n# Complexity\n- Time complexity:\nO(MN*log(MN)) \n\n- Space complexity:\nO(MN) \n\nhttps://leetcode.com/problems/minimum-time-to-visit-a-cell-in-a-grid/submissions/1465730112/?envType=daily-question&envId=2024-11-29\n\n# Code\n```cpp []\nclass Solution {\n    int factor = 1024;\n    vector<int> dir = {-1,0,1,0,-1};\npublic:\n    int minimumTime(vector<vector<int>>& grid) {\n        if(grid[0][1] > 1 && grid[1][0] > 1) return -1;\n        int m = grid.size();\n        int n = grid[0].size();\n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n        pq.push({0,0});\n        grid[0][0] = -1;\n        while(!pq.empty()){\n            auto [cost, pos] = pq.top();\n            pq.pop();\n            int x = pos / factor;\n            int y = pos % factor;\n            if(x == m-1 && y == n-1)\n                return cost;\n            for(int i=0; i<4; ++i){\n                int newx = x + dir[i];\n                int newy = y + dir[i+1];\n                if(newx>=0 && newx<m && newy>=0 && newy<n && grid[newx][newy] != -1){\n                    int newcost = cost + 1;\n                    if(newcost < grid[newx][newy]){\n                        if((grid[newx][newy] - newcost) % 2 == 1)\n                            newcost = grid[newx][newy] + 1;\n                        else\n                            newcost = grid[newx][newy];\n                    }\n                    pq.push({newcost, (newx * factor + newy)});\n                    grid[newx][newy] = -1;\n                }\n            }\n        }\n        return -1000; // will no go to here\n    }\n};\n```
['C++']