diff --git a/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README.md b/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README.md index 95200a5adb14c..7e11869160279 100644 --- a/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README.md +++ b/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README.md @@ -253,6 +253,76 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` +#### TypeScript + +```ts +function minimumTime(grid: number[][]): number { + if (grid[0][1] > 1 && grid[1][0] > 1) return -1; + + const [m, n] = [grid.length, grid[0].length]; + const DIRS = [-1, 0, 1, 0, -1]; + const q = new MinPriorityQueue({ priority: ([x]) => x }); + const dist: number[][] = Array.from({ length: m }, () => + new Array(n).fill(Number.POSITIVE_INFINITY), + ); + dist[0][0] = 0; + q.enqueue([0, 0, 0]); + + while (true) { + const [t, i, j] = q.dequeue().element; + if (i === m - 1 && j === n - 1) return t; + + for (let k = 0; k < 4; k++) { + const [x, y] = [i + DIRS[k], j + DIRS[k + 1]]; + if (x < 0 || x >= m || y < 0 || y >= n) continue; + + let nt = t + 1; + if (nt < grid[x][y]) { + nt = grid[x][y] + ((grid[x][y] - nt) % 2); + } + if (nt < dist[x][y]) { + dist[x][y] = nt; + q.enqueue([nt, x, y]); + } + } + } +} +``` + +#### JavaScript + +```js +function minimumTime(grid) { + if (grid[0][1] > 1 && grid[1][0] > 1) return -1; + + const [m, n] = [grid.length, grid[0].length]; + const DIRS = [-1, 0, 1, 0, -1]; + const q = new MinPriorityQueue({ priority: ([x]) => x }); + const dist = Array.from({ length: m }, () => new Array(n).fill(Number.POSITIVE_INFINITY)); + dist[0][0] = 0; + q.enqueue([0, 0, 0]); + + while (true) { + const [t, i, j] = q.dequeue().element; + if (i === m - 1 && j === n - 1) return t; + + for (let k = 0; k < 4; k++) { + const [x, y] = [i + DIRS[k], j + DIRS[k + 1]]; + if (x < 0 || x >= m || y < 0 || y >= n) continue; + + let nt = t + 1; + if (nt < grid[x][y]) { + nt = grid[x][y] + ((grid[x][y] - nt) % 2); + } + if (nt < dist[x][y]) { + dist[x][y] = nt; + q.enqueue([nt, x, y]); + } + } + } +} +``` + diff --git a/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README_EN.md b/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README_EN.md index 1b7a3d7fa9251..4da803f6954cf 100644 --- a/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README_EN.md +++ b/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README_EN.md @@ -72,7 +72,7 @@ The final time is 7. It can be shown that it is the minimum time possible.

 

-