Skip to content

Commit f14ff5c

Browse files
author
hasibulislam999
committed
Minimum Time to Visit a Cell in a Grid problem solved
1 parent 3d6e289 commit f14ff5c

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* Title: Minimum Time to Visit a Cell in a Grid
3+
* Description: You are given a m x n matrix grid consisting of non-negative integers where grid[row][col] represents the minimum time required to be able to visit the cell (row, col), which means you can visit the cell (row, col) only when the time you visit it is greater than or equal to grid[row][col].
4+
* Author: Hasibul Islam
5+
* Date: 04/05/2023
6+
*/
7+
8+
/**
9+
* @param {number[][]} grid
10+
* @return {number}
11+
*/
12+
var minimumTime = function (grid) {
13+
if (grid[0][1] > 1 && grid[1][0] > 1) {
14+
return -1;
15+
}
16+
const dp = new Array(grid.length)
17+
.fill()
18+
.map((_) => new Array(grid[0].length).fill());
19+
const dir = [1, 0, -1, 0, 1];
20+
const pq = new MinPriorityQueue({
21+
compare: (a, b) => a[0] - b[0],
22+
});
23+
pq.enqueue([0, 0, 0]);
24+
while (pq.size() > 0) {
25+
// Pick the node with the min potential value of time to visit
26+
const [val, i, j] = pq.dequeue();
27+
if (dp[i][j] != null) {
28+
continue;
29+
}
30+
dp[i][j] = val;
31+
if (i === grid.length - 1 && j === grid[0].length - 1) {
32+
break;
33+
}
34+
for (let k = 0; k < 4; ++k) {
35+
const [ni, nj] = [i + dir[k], j + dir[k + 1]];
36+
if (
37+
ni >= 0 &&
38+
nj >= 0 &&
39+
ni < grid.length &&
40+
nj < grid[0].length &&
41+
dp[ni][nj] == null
42+
) {
43+
// 1 + dp[i][j]: Move 1 step from [i, j] to [ni, nj];
44+
// grid[ni][nj] + (grid[ni][nj] & 1 ^ (ni+nj) & 1): After some back and forth in [i, j], finally reach the time
45+
// of grid[ni][nj], depending on its value and position, we may need to add 1 to it.
46+
const pVal = Math.max(
47+
1 + dp[i][j],
48+
grid[ni][nj] + ((grid[ni][nj] & 1) ^ ((ni + nj) & 1))
49+
);
50+
pq.enqueue([pVal, ni, nj]);
51+
}
52+
}
53+
}
54+
return dp[grid.length - 1][grid[0].length - 1];
55+
};

0 commit comments

Comments
 (0)