Open In App

Rabbit House | Google Kickstart 2021 Round A

Last Updated : 02 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Barbara got really good grades in school last year, so her parents decided to gift her with a pet rabbit. She was so excited that she built a house for the rabbit, which can be seen as a 2D grid with RR rows and CC columns. Rabbits love to jump, so Barbara stacked several boxes on several cells of the grid. Each box is a cube with equal dimensions, which match exactly the dimensions of a cell of the grid. However, Barbara soon realizes that it may be dangerous for the rabbit to make jumps of height greater than 11 box, so she decides to avoid that by making some adjustments to the house. For every pair of adjacent cells, Barbara would like that their absolute difference in height be at most 11 box. Two cells are considered adjacent if they share a common side. As all the boxes are superglued, Barbara cannot remove any boxes that are there initially, however she can add boxes on top of them. She can add as many boxes as she wants, to as many cells as she wants (which may be zero). Help her determine what is the minimum total number of boxes to be added so that the rabbit’s house is safe.

OR

Given a matrix of R rows and M columns. Make the absolute difference between the adjacent cells less than or equal to 1 by only increasing the cell value. The total increment done on cells should be minimized. The task is to return the minimum increment operations done.

Example:

Input: [[0 0 0], 
            [0 2 0], 
           [0 0 0]]
Output: 4
Explanation: the cell in the middle of the grid has an absolute difference in height of 2, the height of all its four adjacent cells is increased  by exactly 1 unit so that the absolute difference between 
any pair of adjacent cells will be at most 1. Resultant matrix will be:
           [[0 1 0], 
            [1 2 1], 
           [0 1 0]]

Input: [[1 0 5 4 2], 
           [1 5 6 4 8], 
          [2 3 4 2 1], 
          [2 3 4 9 8]]
  
Output: 52
Explanation: Resultant matrix will be: [[3 4 5 6 7],  
                                                             [4 5 6 7 8 ], 
                                                             [5 6 7 8 7],  
                                                             [6 7 8 9 8]]

Approach: Given problem can be solved using multisource dijkstra’s algorithm. The approach is to store the cells with the largest values in a priority queue, pop out the priority queue one by one and update the adjacent cells accordingly, while updating the cell value we will also update our priority queue.

Below is the implementation of the above approach:

C++




// C++ implementation for the above approach
#include <bits/stdc++.h>
using namespace std;
 
void solve(long long int r, long long int c,
           vector<vector<long long int> >& grid)
{
    priority_queue<pair<long long int,
                        pair<long long int, long long int> > >
        pq;
 
    for (long long int i = 0; i < r; i++) {
        for (long long int j = 0; j < c; j++) {
            pq.push(make_pair(grid[i][j],
                              make_pair(i, j)));
        }
    }
 
    long long int res = 0;
 
    while (!pq.empty()) {
        long long int height = pq.top().first,
                      i = pq.top().second.first,
                      j = pq.top().second.second;
        pq.pop();
        if (height != grid[i][j])
            continue;
        if (i == 0) {
            // Down
            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.push(make_pair(height - 1,
                                      make_pair(i + 1, j)));
                }
            }
            // Left
            if (j != 0) {
                if (grid[i][j - 1] < height - 1) {
 
                    res += height - 1 - grid[i][j - 1];
                    grid[i][j - 1] = height - 1;
 
                    pq.push(make_pair(height - 1,
                                      make_pair(i, j - 1)));
                }
            }
            // Right
            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.push(make_pair(height - 1,
                                      make_pair(i, j + 1)));
                }
            }
        }
        else if (i == r - 1) {
            // Up
            if (i != 0) {
                if (grid[i - 1][j] < height - 1) {
 
                    res += height - 1 - grid[i - 1][j];
                    grid[i - 1][j] = height - 1;
 
                    pq.push(make_pair(height - 1,
                                      make_pair(i - 1, j)));
                }
            }
            // Left
            if (j != 0) {
                if (grid[i][j - 1] < height - 1) {
 
                    res += height - 1 - grid[i][j - 1];
                    grid[i][j - 1] = height - 1;
 
                    pq.push(make_pair(height - 1,
                                      make_pair(i, j - 1)));
                }
            }
            // Right
            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.push(make_pair(height - 1,
                                      make_pair(i, j + 1)));
                }
            }
        }
        else {
            // Down
            if (grid[i + 1][j] < height - 1) {
 
                res += height - 1 - grid[i + 1][j];
                grid[i + 1][j] = height - 1;
 
                pq.push(make_pair(height - 1,
                                  make_pair(i + 1, j)));
            }
            // Up
            if (grid[i - 1][j] < height - 1) {
 
                res += height - 1 - grid[i - 1][j];
                grid[i - 1][j] = height - 1;
 
                pq.push(make_pair(height - 1,
                                  make_pair(i - 1, j)));
            }
            // Left
            if (j != 0) {
                if (grid[i][j - 1] < height - 1) {
 
                    res += height - 1 - grid[i][j - 1];
                    grid[i][j - 1] = height - 1;
 
                    pq.push(make_pair(height - 1,
                                      make_pair(i, j - 1)));
                }
            }
            // Right
            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.push(make_pair(height - 1,
                                      make_pair(i, j + 1)));
                }
            }
        }
    }
    cout << res;
}
 
// Driver code
int main()
{
 
    long long int r = 4, c = 5;
    vector<vector<long long int> > grid{ { 1, 0, 5, 4, 2 },
                                         { 1, 5, 6, 4, 8 },
                                         { 2, 3, 4, 2, 1 },
                                         { 2, 3, 4, 9, 8 } };
 
    solve(r, c, grid);
}


Java




// Java implementation for the above approach
import java.util.*;
 
public class Main {
 
    static class Cell {
        long height;
        int row;
        int col;
 
        Cell(long height, int row, int col)
        {
            this.height = height;
            this.row = row;
            this.col = col;
        }
    }
 
    // Comparator for priority queue, comparing cells based
    // on height
    static class PriorityQueueComparator
        implements Comparator<Cell> {
        public int compare(Cell cell1, Cell cell2)
        {
            return Long.compare(cell2.height, cell1.height);
        }
    }
 
    // Generic PriorityQueue implementation
    static class PriorityQueue<T> {
        private List<T> heap;
        private Comparator<T> comparator;
 
        public PriorityQueue(Comparator<T> comparator)
        {
            this.heap = new ArrayList<>();
            this.comparator = comparator;
        }
 
        public int size() { return heap.size(); }
 
        public void enqueue(T item)
        {
            heap.add(item);
            int i = heap.size() - 1;
 
            // Heapify upwards to maintain heap property
            while (i > 0) {
                int parent = (i - 1) / 2;
 
                if (comparator.compare(heap.get(parent),
                                       heap.get(i))
                    <= 0)
                    break;
 
                swap(i, parent);
                i = parent;
            }
        }
 
        public T dequeue()
        {
            if (heap.isEmpty())
                throw new NoSuchElementException(
                    "PriorityQueue is empty");
 
            T result = heap.get(0);
            int last = heap.size() - 1;
            heap.set(0, heap.get(last));
            heap.remove(last);
 
            int i = 0;
            // Heapify downwards to maintain heap property
            while (true) {
                int leftChild = i * 2 + 1;
                int rightChild = i * 2 + 2;
                int smallest = i;
 
                if (leftChild < heap.size()
                    && comparator.compare(
                           heap.get(leftChild),
                           heap.get(smallest))
                           < 0)
                    smallest = leftChild;
 
                if (rightChild < heap.size()
                    && comparator.compare(
                           heap.get(rightChild),
                           heap.get(smallest))
                           < 0)
                    smallest = rightChild;
 
                if (smallest == i)
                    break;
 
                swap(i, smallest);
                i = smallest;
            }
 
            return result;
        }
 
        private void swap(int i, int j)
        {
            T temp = heap.get(i);
            heap.set(i, heap.get(j));
            heap.set(j, temp);
        }
    }
 
    // Function to solve the problem
    static void solve(int r, int c, long[][] grid)
    {
        PriorityQueue<Cell> pq = new PriorityQueue<>(
            new PriorityQueueComparator());
 
        // Enqueue all cells into the priority queue
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                pq.enqueue(new Cell(grid[i][j], i, j));
            }
        }
 
        long res = 0;
 
        // Process cells in priority order
        while (pq.size() > 0) {
            Cell cell = pq.dequeue();
            long height = cell.height;
            int i = cell.row;
            int j = cell.col;
 
            // Skip if the height has changed since
            // enqueueing
            if (height != grid[i][j])
                continue;
 
            // Update neighboring cells and accumulate
            // result based on the conditions provided
            // (moving down, up, left, right)
            // Note: Conditions are checked to avoid array
            // out-of-bounds errors and to ensure that the
            // heights are increased appropriately. The
            // updated cells are then enqueued back into the
            // priority queue.
 
            // Handle different boundary cases for updating
            // neighboring cells based on the current
            // position in the grid
 
            if (i == 0) {
                // Current cell is in the top row
 
                // Down
                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(
                            new Cell(height - 1, i + 1, j));
                    }
                }
                // Left
                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(
                            new Cell(height - 1, i, j - 1));
                    }
                }
                // Right
                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(
                            new Cell(height - 1, i, j + 1));
                    }
                }
            }
            else if (i == r - 1) {
                // Current cell is in the bottom row
 
                // Up
                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(
                            new Cell(height - 1, i - 1, j));
                    }
                }
                // Left
                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(
                            new Cell(height - 1, i, j - 1));
                    }
                }
                // Right
                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(
                            new Cell(height - 1, i, j + 1));
                    }
                }
            }
            else {
                // Current cell is in a middle row
 
                // Down
                if (grid[i + 1][j] < height - 1) {
                    res += height - 1 - grid[i + 1][j];
                    grid[i + 1][j] = height - 1;
                    pq.enqueue(
                        new Cell(height - 1, i + 1, j));
                }
                // Up
                if (grid[i - 1][j] < height - 1) {
                    res += height - 1 - grid[i - 1][j];
                    grid[i - 1][j] = height - 1;
                    pq.enqueue(
                        new Cell(height - 1, i - 1, j));
                }
                // Left
                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(
                            new Cell(height - 1, i, j - 1));
                    }
                }
                // Right
                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(
                            new Cell(height - 1, i, j + 1));
                    }
                }
            }
        }
        System.out.println(res);
    }
 
    public static void main(String[] args)
    {
        int r = 4, c = 5;
        long[][] grid = { { 1, 0, 5, 4, 2 },
                          { 1, 5, 6, 4, 8 },
                          { 2, 3, 4, 2, 1 },
                          { 2, 3, 4, 9, 8 } };
 
        // Call the solve function with the given grid
        // dimensions and data
        solve(r, c, grid);
    }
}


Python3




# Python program for the above approach
from queue import PriorityQueue
from typing import List, Tuple
 
def solve(r: int, c: int, grid: List[List[int]]) -> int:
    pq = PriorityQueue()
 
    for i in range(r):
        for j in range(c):
            pq.put((grid[i][j], (i, j)))
 
    res = 0
 
    while not pq.empty():
        height, (i, j) = pq.get()
        if height != grid[i][j]:
            continue
        if i == 0:
            # Down
            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.put((height - 1, (i + 1, j)))
            # Left
            if j != 0:
                if grid[i][j - 1] < height - 1:
                    res += height - 1 - grid[i][j - 1]
                    grid[i][j - 1] = height - 1
                    pq.put((height - 1, (i, j - 1)))
            # Right
            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.put((height - 1, (i, j + 1)))
        elif i == r - 1:
            # Up
            if i != 0:
                if grid[i - 1][j] < height - 1:
                    res += height - 1 - grid[i - 1][j]
                    grid[i - 1][j] = height - 1
                    pq.put((height - 1, (i - 1, j)))
            # Left
            if j != 0:
                if grid[i][j - 1] < height - 1:
                    res += height - 1 - grid[i][j - 1]
                    grid[i][j - 1] = height - 1
                    pq.put((height - 1, (i, j - 1)))
            # Right
            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.put((height - 1, (i, j + 1)))
        else:
            # Down
            if grid[i + 1][j] < height - 1:
                res += height - 1 - grid[i + 1][j]
                grid[i + 1][j] = height - 1
                pq.put((height - 1, (i + 1, j)))
            # Up
            if grid[i - 1][j] < height - 1:
                res += height - 1 - grid[i - 1][j]
                grid[i - 1][j] = height - 1
                pq.put((height - 1, (i - 1, j)))
            # Left
            if j != 0:
                if grid[i][j - 1] < height - 1:
                    res += height - 1 - grid[i][j - 1]
                    grid[i][j - 1] = height - 1
                    pq.put((height - 1, (i, j - 1)))
            # Right
            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.put((height - 1, (i, j + 1)))
    return res
 
 
# Example usage
r = 4
c = 5
grid = [[1, 0, 5, 4, 2],
        [1, 5, 6, 4, 8],
        [2, 3, 4, 2, 1],
        [2, 3, 4, 9, 8]]
print(solve(r, c, grid))
 
# This code is contributed by Potta Lokesh


C#




using System;
using System.Collections.Generic;
 
class Program
{
    static void Solve(long r, long c, List<List<long>> grid)
    {
        var pq = new PriorityQueue<Tuple<long, Tuple<long, long>>>(
            Comparer<Tuple<long, Tuple<long, long>>>.Create((a, b) => b.Item1.CompareTo(a.Item1))
        );
 
        for (long i = 0; i < r; i++)
        {
            for (long j = 0; j < c; j++)
            {
                pq.Enqueue(new Tuple<long, Tuple<long, long>>(grid[(int)i][(int)j], new Tuple<long, long>(i, j)));
            }
        }
 
        long res = 0;
 
        while (pq.Count > 0)
        {
            long height = pq.Peek().Item1;
            long i = pq.Peek().Item2.Item1;
            long j = pq.Peek().Item2.Item2;
            pq.Dequeue();
 
            if (height != grid[(int)i][(int)j])
                continue;
 
            if (i == 0)
            {
                // Down
                if (i != r - 1)
                {
                    if (grid[(int)i + 1][(int)j] < height - 1)
                    {
                        res += height - 1 - grid[(int)i + 1][(int)j];
                        grid[(int)i + 1][(int)j] = height - 1;
 
                        pq.Enqueue(new Tuple<long, Tuple<long, long>>(height - 1, new Tuple<long, long>(i + 1, j)));
                    }
                }
                // Left
                if (j != 0)
                {
                    if (grid[(int)i][(int)j - 1] < height - 1)
                    {
                        res += height - 1 - grid[(int)i][(int)j - 1];
                        grid[(int)i][(int)j - 1] = height - 1;
 
                        pq.Enqueue(new Tuple<long, Tuple<long, long>>(height - 1, new Tuple<long, long>(i, j - 1)));
                    }
                }
                // Right
                if (j != c - 1)
                {
                    if (grid[(int)i][(int)j + 1] < height - 1)
                    {
                        res += height - 1 - grid[(int)i][(int)j + 1];
                        grid[(int)i][(int)j + 1] = height - 1;
 
                        pq.Enqueue(new Tuple<long, Tuple<long, long>>(height - 1, new Tuple<long, long>(i, j + 1)));
                    }
                }
            }
            else if (i == r - 1)
            {
                // Up
                if (i != 0)
                {
                    if (grid[(int)i - 1][(int)j] < height - 1)
                    {
                        res += height - 1 - grid[(int)i - 1][(int)j];
                        grid[(int)i - 1][(int)j] = height - 1;
 
                        pq.Enqueue(new Tuple<long, Tuple<long, long>>(height - 1, new Tuple<long, long>(i - 1, j)));
                    }
                }
                // Left
                if (j != 0)
                {
                    if (grid[(int)i][(int)j - 1] < height - 1)
                    {
                        res += height - 1 - grid[(int)i][(int)j - 1];
                        grid[(int)i][(int)j - 1] = height - 1;
 
                        pq.Enqueue(new Tuple<long, Tuple<long, long>>(height - 1, new Tuple<long, long>(i, j - 1)));
                    }
                }
                // Right
                if (j != c - 1)
                {
                    if (grid[(int)i][(int)j + 1] < height - 1)
                    {
                        res += height - 1 - grid[(int)i][(int)j + 1];
                        grid[(int)i][(int)j + 1] = height - 1;
 
                        pq.Enqueue(new Tuple<long, Tuple<long, long>>(height - 1, new Tuple<long, long>(i, j + 1)));
                    }
                }
            }
            else
            {
                // Down
                if (grid[(int)i + 1][(int)j] < height - 1)
                {
                    res += height - 1 - grid[(int)i + 1][(int)j];
                    grid[(int)i + 1][(int)j] = height - 1;
 
                    pq.Enqueue(new Tuple<long, Tuple<long, long>>(height - 1, new Tuple<long, long>(i + 1, j)));
                }
                // Up
                if (grid[(int)i - 1][(int)j] < height - 1)
                {
                    res += height - 1 - grid[(int)i - 1][(int)j];
                    grid[(int)i - 1][(int)j] = height - 1;
 
                    pq.Enqueue(new Tuple<long, Tuple<long, long>>(height - 1, new Tuple<long, long>(i - 1, j)));
                }
                // Left
                if (j != 0)
                {
                    if (grid[(int)i][(int)j - 1] < height - 1)
                    {
                        res += height - 1 - grid[(int)i][(int)j - 1];
                        grid[(int)i][(int)j - 1] = height - 1;
 
                        pq.Enqueue(new Tuple<long, Tuple<long, long>>(height - 1, new Tuple<long, long>(i, j - 1)));
                    }
                }
                // Right
                if (j != c - 1)
                {
                    if (grid[(int)i][(int)j + 1] < height - 1)
                    {
                        res += height - 1 - grid[(int)i][(int)j + 1];
                        grid[(int)i][(int)j + 1] = height - 1;
 
                        pq.Enqueue(new Tuple<long, Tuple<long, long>>(height - 1, new Tuple<long, long>(i, j + 1)));
                    }
                }
            }
        }
 
        Console.WriteLine(res);
    }
 
    static void Main()
    {
        long r = 4, c = 5;
        var grid = new List<List<long>>
        {
            new List<long> {1, 0, 5, 4, 2},
            new List<long> {1, 5, 6, 4, 8},
            new List<long> {2, 3, 4, 2, 1},
            new List<long> {2, 3, 4, 9, 8}
        };
 
        Solve(r, c, grid);
    }
}
 
// PriorityQueue implementation
public class PriorityQueue<T>
{
    private readonly List<T> heap;
    private readonly IComparer<T> comparer;
 
    public PriorityQueue() : this(null) { }
 
    public PriorityQueue(IComparer<T> comparer) : this(16, comparer) { }
 
    public PriorityQueue(int capacity, IComparer<T> comparer)
    {
        this.heap = new List<T>(capacity);
        this.comparer = comparer ?? Comparer<T>.Default;
    }
 
    public void Enqueue(T item)
    {
        heap.Add(item);
        int i = Count - 1;
        while (i > 0)
        {
            int parent = (i - 1) / 2;
            if (comparer.Compare(heap[parent], item) <= 0)
                break;
 
            heap[i] = heap[parent];
            i = parent;
        }
        heap[i] = item;
    }
 
    public T Dequeue()
    {
        T target = heap[0];
        T root = heap[Count - 1];
        heap.RemoveAt(Count - 1);
        if (Count > 0)
        {
            int i = 0;
            while (i * 2 + 1 < Count)
            {
                int leftChild = i * 2 + 1;
                int rightChild = i * 2 + 2;
                int swap = leftChild;
                if (rightChild < Count && comparer.Compare(heap[leftChild], heap[rightChild]) > 0)
                    swap = rightChild;
 
                if (comparer.Compare(heap[swap], root) >= 0)
                    break;
 
                heap[i] = heap[swap];
                i = swap;
            }
            heap[i] = root;
        }
        return target;
    }
 
    public T Peek()
    {
        if (Count == 0)
            throw new InvalidOperationException("PriorityQueue is empty");
        return heap[0];
    }
 
    public int Count { get { return heap.Count; } }
}


Javascript




// JavaScript program for the above approach
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) {
            // Down
            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]]);
                }
            }
            // Left
            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]]);
                }
            }
            // Right
            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) {
            // Up
            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]]);
                }
            }
            // Left
            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]]);
                }
            }
            // Right
            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 {
            // Down
            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]]);
            }
            // Up
            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]]);
            }
            // Left
            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]]);
            }
            // Right
            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;
}
 
// Example usage
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));
 
// Contributed by adityasharmadev01


Output

52

Time Complexity: O(RM * Log(RM))
Auxiliary Space: O(RM)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads