Skip to content

Commit 38a4c67

Browse files
authored
Create Solution.js
1 parent 4c07d50 commit 38a4c67

File tree

1 file changed

+101
-0
lines changed
  • solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid

1 file changed

+101
-0
lines changed
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
class MinHeap {
2+
constructor() {
3+
this.heap = [];
4+
}
5+
6+
push(element) {
7+
this.heap.push(element);
8+
this._heapifyUp();
9+
}
10+
11+
pop() {
12+
if (this.size() === 1) return this.heap.pop();
13+
const top = this.heap[0];
14+
this.heap[0] = this.heap.pop();
15+
this._heapifyDown();
16+
return top;
17+
}
18+
19+
peek() {
20+
return this.heap[0];
21+
}
22+
23+
size() {
24+
return this.heap.length;
25+
}
26+
27+
_heapifyUp() {
28+
let index = this.heap.length - 1;
29+
while (index > 0) {
30+
const parentIndex = Math.floor((index - 1) / 2);
31+
if (this.heap[index][0] >= this.heap[parentIndex][0]) break;
32+
[this.heap[index], this.heap[parentIndex]] = [this.heap[parentIndex], this.heap[index]];
33+
index = parentIndex;
34+
}
35+
}
36+
37+
_heapifyDown() {
38+
let index = 0;
39+
const length = this.heap.length;
40+
while (true) {
41+
const leftChild = 2 * index + 1;
42+
const rightChild = 2 * index + 2;
43+
let smallest = index;
44+
45+
if (leftChild < length && this.heap[leftChild][0] < this.heap[smallest][0]) {
46+
smallest = leftChild;
47+
}
48+
if (rightChild < length && this.heap[rightChild][0] < this.heap[smallest][0]) {
49+
smallest = rightChild;
50+
}
51+
if (smallest === index) break;
52+
53+
[this.heap[index], this.heap[smallest]] = [this.heap[smallest], this.heap[index]];
54+
index = smallest;
55+
}
56+
}
57+
}
58+
59+
/**
60+
* @param {number[][]} grid
61+
* @return {number}
62+
*/
63+
var minimumTime = function(grid) {
64+
const m = grid.length;
65+
const n = grid[0].length;
66+
67+
if (grid[0][1] > 1 && grid[1][0] > 1) return -1;
68+
69+
const dist = Array.from({ length: m }, () => Array(n).fill(Infinity));
70+
dist[0][0] = 0;
71+
72+
const pq = new MinHeap();
73+
pq.push([0, 0, 0]);
74+
75+
const directions = [-1, 0, 1, 0, -1];
76+
77+
while (pq.size() > 0) {
78+
const [t, i, j] = pq.pop();
79+
80+
if (i === m - 1 && j === n - 1) return t;
81+
82+
for (let d = 0; d < 4; d++) {
83+
const x = i + directions[d];
84+
const y = j + directions[d + 1];
85+
86+
if (x >= 0 && x < m && y >= 0 && y < n) {
87+
let nt = t + 1;
88+
if (nt < grid[x][y]) {
89+
nt = grid[x][y] + (grid[x][y] - nt) % 2;
90+
}
91+
92+
if (nt < dist[x][y]) {
93+
dist[x][y] = nt;
94+
pq.push([nt, x, y]);
95+
}
96+
}
97+
}
98+
}
99+
100+
return -1;
101+
};

0 commit comments

Comments
 (0)