97% in time, 70 in space using djikistra
\n\n# Approach\nIf you are able to move once, you can reach any cell because you can just oscillate between 2 cells. If you are at i,j at an odd time let\'s say
\n\n# Approach\nIf you are able to move once, you can reach any cell because you can just oscillate between 2 cells. If you are at i,j at an odd time let\'s say 5 and you want to go to i+1, j and grid[i+1][j] = 9 then you can\'t reach grid[i+1][j] at 9 time because oscillation takes 2 seconds. Hence, you will reach grid[i+1][j] at 10th second. \n\n\nUse standard djikistra algorithm and the above mentioned formula to get to the last position. \n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(m*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    int minimumTime(vector<vector<int>>& grid) {\n        priority_queue<pair<int, pair<int,int>>, vector<pair<int, pair<int,int>>>, greater<>> pq;\n        pq.emplace(0, make_pair(0,0));\n        int m  = grid.size();\n        int n = grid[0].size();\n        vector<vector<int>> visited(m, vector<int>(n, -1));\n        visited[0][0] = 0;\n        vector<pair<int,int>> dir = {{1,0}, {0,1}, {-1, 0}, {0,-1}};\n        if(grid[1][0] > 1 && grid[0][1] > 1) {\n            return -1;\n        }\n        while(!pq.empty()) {\n            auto [time, p] = pq.top();\n            pq.pop();\n            if(p.first == m-1 && p.second == n-1) {\n                return time;\n            }\n            int i = p.first;\n            int j = p.second;\n            for(int ptr = 0;ptr<4;ptr++) {\n                int resi = i + dir[ptr].first;\n                int resj = j + dir[ptr].second;\n                if(resi>=0 && resj>=0 && resi < m && resj<n) {\n                    int timet = max(time+1, grid[resi][resj] + ((time%2 == grid[resi][resj]%2) ? 1 : 0));\n                    if((visited[resi][resj] == -1 || visited[resi][resj] > timet)) {\n                        visited[resi][resj] = timet;\n                        pq.emplace(timet, make_pair(resi, resj));\n                    }\n                }\n            }\n        }\n        return -1;\n    }\n};\n```
['C++']