Matrix Cells in Distance Order

We are given a matrix with R rows and C columns have cells with integer coordinates (r, c), where 0 <= r < R and 0 <= c < C.

Additionally, we are given a cell in that matrix with coordinates (r0, c0).

Return the coordinates of all cells in the matrix, sorted by their distance from (r0, c0) from smallest distance to largest distance.  Here, the distance between two cells (r1, c1) and (r2, c2) is the Manhattan distance, |r1 - r2| + |c1 - c2|.  (You may return the answer in any order that satisfies this condition.)

Example:

Input: R = 1, C = 2, r0 = 0, c0 = 0
Output: [[0,0],[0,1]]
Explanation: The distances from (r0, c0) to other cells are: [0,1]

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

vector<vector<int>> allCellsDistOrder(int Rint Cint r0int c0)
{
    map<int, vector<pair<intint>>> mp;
    for (int i = 0; i < R; i++)
    {
        for (int j = 0; j < C; j++)
        {
            int dis = abs(i - r0) + abs(j - c0);
            mp[dis].push_back({i, j});
        }
    }
    vector<vector<int>> res;
    for (auto it = mp.begin(); it != mp.end(); it++)
    {
        int j = 0;
        while (j < it->second.size())
        {
            vector<int> v;
            v.push_back(it->second[j].first);
            v.push_back(it->second[j].second);
            res.push_back(v);
            j++;
        }
    }
    return res;
}
int main()
{
    int R = 1, C = 2, r0 = 0, c0 = 0;

    vector<vector<int>> res = allCellsDistOrder(R, C, r0, c0);

    cout << "[";
    for (int i = 0; i < res.size(); i++)
    {
        cout << "[";
        for (int j = 0; j < res[i].size(); j++)
        {
            cout << res[i][j];
            if (j != res[i].size() - 1)
                cout << ",";
        }
        cout << "]";
        if (i != res.size() - 1)
            cout << ",";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment