Dijkstra | BFS + PriorityQueue
Code\n\nconst moves = [[0, -1], [0, 1], [1, 0], [-1, 0]]\n\nfunction minimumTime(grid: number[][]): number {\n    const N = grid.length;\n    const M = grid[0].
# Code\n```\nconst moves = [[0, -1], [0, 1], [1, 0], [-1, 0]]\n\nfunction minimumTime(grid: number[][]): number {\n    const N = grid.length;\n    const M = grid[0].length;\n\n    const check = (x: number, y: number) => x >= 0 && y >= 0 && x < N && y < M;\n\n    let visited: boolean[][] = [...new Array(N)].map(_ => new Array(M).fill(false));\n\n    if(grid[0][1] > 1 && grid[1][0] > 1){\n        return -1\n    }\n    \n    const heap = new MinPriorityQueue()\n    heap.enqueue([0, 0, 0], 0);\n\n    while (heap.size()) {\n        let [i, j, time] = heap.dequeue().element;\n \n        visited[i][j] = true;\n\n        if (i == N -1 && j == M - 1) {\n            return time\n        }\n\n        for (const [diffX, diffY] of moves) {\n            const newX = i + diffX, newY = j + diffY;\n            if (!check(newX, newY)) {\n                continue;\n            }\n\n            if (visited[newX][newY]) {\n                continue;\n            }\n\n            let newTime = time + 1\n            if (time + 1 < grid[newX][newY]) {\n                let diff = grid[newX][newY] - time-1\n                newTime = diff % 2 == 0 ? \n                    grid[newX][newY] : grid[newX][newY] + 1\n                \n            }\n\n            visited[newX][newY] = true;\n            heap.enqueue([newX, newY, newTime], newTime)\n        }\n    }\n\n    return -1;\n};\n\n```
['TypeScript']