class PriorityQueue {
constructor() {
this
.queue = [];
}
enqueue(item) {
let contain =
false
;
for
(let i = 0; i <
this
.queue.length; i++) {
if
(
this
.queue[i][0] > item[0]) {
this
.queue.splice(i, 0, item);
contain =
true
;
break
;
}
}
if
(!contain) {
this
.queue.push(item);
}
}
dequeue() {
return
this
.queue.shift();
}
isEmpty() {
return
this
.queue.length === 0;
}
}
function
solve(r, c, grid) {
const pq =
new
PriorityQueue();
for
(let i = 0; i < r; i++) {
for
(let j = 0; j < c; j++) {
pq.enqueue([grid[i][j],
[i, j]
]);
}
}
let res = 0;
while
(!pq.isEmpty()) {
const [height, [i, j]] = pq.dequeue();
if
(height != grid[i][j]) {
continue
;
}
if
(i == 0) {
if
(i != r - 1) {
if
(grid[i + 1][j] < height - 1) {
res += height - 1 - grid[i + 1][j];
grid[i + 1][j] = height - 1;
pq.enqueue([height - 1, [i + 1, j]]);
}
}
if
(j != 0) {
if
(grid[i][j - 1] < height - 1) {
res += height - 1 - grid[i][j - 1];
grid[i][j - 1] = height - 1;
pq.enqueue([height - 1, [i, j - 1]]);
}
}
if
(j != c - 1) {
if
(grid[i][j + 1] < height - 1) {
res += height - 1 - grid[i][j + 1];
grid[i][j + 1] = height - 1;
pq.enqueue([height - 1, [i, j + 1]]);
}
}
}
else
if
(i === r - 1) {
if
(i !== 0) {
if
(grid[i - 1][j] < height - 1) {
res += height - 1 - grid[i - 1][j];
grid[i - 1][j] = height - 1;
pq.enqueue([height - 1, [i - 1, j]]);
}
}
if
(j !== 0) {
if
(grid[i][j - 1] < height - 1) {
res += height - 1 - grid[i][j - 1];
grid[i][j - 1] = height - 1;
pq.enqueue([height - 1, [i, j - 1]]);
}
}
if
(j !== c - 1) {
if
(grid[i][j + 1] < height - 1) {
res += height - 1 - grid[i][j + 1];
grid[i][j + 1] = height - 1;
pq.enqueue([height - 1, [i, j + 1]]);
}
}
}
else
{
if
(i + 1 < r && grid[i + 1][j] < height - 1) {
res += height - 1 - grid[i + 1][j];
grid[i + 1][j] = height - 1;
pq.enqueue([height - 1, [i + 1, j]]);
}
if
(i - 1 >= 0 && grid[i - 1][j] < height - 1) {
res += height - 1 - grid[i - 1][j];
grid[i - 1][j] = height - 1;
pq.enqueue([height - 1, [i - 1, j]]);
}
if
(j != 0 && grid[i][j - 1] < height - 1) {
res += height - 1 - grid[i][j - 1];
grid[i][j - 1] = height - 1;
pq.enqueue([height - 1, [i, j - 1]]);
}
if
(j != c - 1 && grid[i][j + 1] < height - 1) {
res += height - 1 - grid[i][j + 1];
grid[i][j + 1] = height - 1;
pq.enqueue([height - 1, [i, j + 1]]);
}
}
}
return
res;
}
const r = 4;
const c = 5;
const grid = [
[1, 0, 5, 4, 2],
[1, 5, 6, 4, 8],
[2, 3, 4, 2, 1],
[2, 3, 4, 9, 8]
];
console.log(solve(r, c, grid));