JAVA solution | PriorityQueue
\n\nclass Solution {\n    \n\tpublic int minimumTime(int[][] grid) {\n        \n        \n        int n = grid.length, m = grid[0].length;\n        if(grid[0][0
\n\nclass Solution {\n    \n\tpublic int minimumTime(int[][] grid) {\n        \n        \n        int n = grid.length, m = grid[0].length;\n        if(grid[0][0] > t) return -1;\n        if(grid[0][1] > 1 && grid[1][0] > 1) return -1;\n        \n        int[][] dir = {{-1,0}, {1,0}, {0,-1}, {0,1}};\n        \n        PriorityQueue<int[]> q = new PriorityQueue<>( (a, b)->(a[2]-b[2]) );\n        boolean[][] vis = new boolean[n][m];\n        q.offer(new int[]{0, 0, 0});\n        \n        while(!q.isEmpty()){\n            int[] e = q.remove();\n            \n            vis[e[0]][e[1]] = true;\n            \n            if(e[0]  == n-1 && e[1] == m-1) return e[2];\n            \n            for(int[] d: dir){\n                int new_x = e[0]+d[0], new_y = e[1]+d[1];\n                \n                if(new_x < 0 || new_y < 0 || new_x >= n || new_y >= m || vis[new_x][new_y]) continue;\n                vis[new_x][new_y] = true;\n                int diff = grid[new_x][new_y]-e[2];\n                \n                if(diff <= 1){\n                    q.offer(new int[]{new_x, new_y, e[2]+1});\n                }else{\n                    if(diff%2 == 0){\n                        q.offer(new int[]{new_x, new_y, e[2]+diff+1});\n                    }else{\n                        q.offer(new int[]{new_x, new_y, e[2]+diff});\n                    }\n                }\n                \n            }\n            \n        }\n        return -1;\n    }\n}
[]