Editorial for Caner: The Way of Water


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.
#include <bits/stdc++.h>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    // cout << setprecision(numeric_limits<double> :: digits10);

    int rowCount, columnCount;
    cin >> rowCount >> columnCount;

    int heightMap[rowCount][columnCount];
    for (int i = 0; i < rowCount; i++)
        for (int j = 0; j < columnCount; j++)
            cin >> heightMap[i][j];

    int volume = 0;
    int level = 0;
    bool visited[rowCount][columnCount];
    memset(visited, false, rowCount * columnCount * sizeof(bool));
    multimap<int, pair<int, int>> queue;

    // Add all the boundary cells to the queue
    for (int i = 0; i < rowCount; i++)
    {
        for (int j = 0; j < columnCount; j++)
        {
            if (i == 0 || j == 0 || i == rowCount - 1 || j == columnCount - 1)
            {
                queue.emplace(heightMap[i][j], make_pair(i, j));
                visited[i][j] = true;
            }
        }
    }

    // BFS
    int dirs[4][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
    while (!queue.empty())
    {
        pair<int, int> cur = queue.begin() -> second;
        int priority = queue.begin() -> first;
        queue.erase(queue.begin());

        int x = cur.first;
        int y = cur.second;
        level = max(level, priority);
        for (auto & dir : dirs)
        {
            int nx = x + dir[0];
            int ny = y + dir[1];
            if (nx >= 0 && nx < rowCount && ny >= 0 && ny < columnCount && !visited[nx][ny])
            {
                queue.emplace(heightMap[nx][ny], make_pair(nx, ny));
                volume += max(0, level - heightMap[nx][ny]);

                visited[nx][ny] = true;
            }
        }
    }

    cout << volume << '\n';
    // cout << result << endl;
    return 0;
}