🚀 Optimized Approach to Sort Grid Cells by Distance || C++ || Sorting
💡IntuitionThe intuition was to find the distance of all the cells from the given rCenter and cCenter and then sort the cells according to their distances.🧪 Appr
# 💡Intuition
The intuition was to find the **distance of all the cells from the given rCenter and cCenter and then sort the cells** according to their distances.

---
# 🧪 Approach
- I took a 2D vector ans to store the final answer and a vector v of `pair<int, pair<int, int>>` to store the `distance` and the corresponding `row` and `column` number.
- So basically, while we traverse the matrix of `rows * col` size, `v.first` stores the distance of the current cell from `rCenter` & `cCenter`.`v.second.first` store the row number and `v.second.second` stores the column number. 
- Then we sort the elements of the  vector `v` according to their first element i.e `distances`.
- At the end, we traverse the vector `v` and push the `row` number and `col` number in a sorted order.
---
# ⌛📦 Complexity
- Time complexity: `O(nlogn)` or `O((rows×cols)log(rows×cols))`


- Space complexity: `O(rows*cols)`

# Code
```cpp []
class Solution {
public:
    vector<vector<int>> allCellsDistOrder(int rows, int cols, int rc, int cc) {
        vector<vector<int>> ans;
        vector<pair<int, pair<int, int>>> v;
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                int distance = abs(i - rc) + abs(j - cc);
                v.push_back({distance, {i, j}});
            }
        }
        sort(v.begin(), v.end());
        for (int i = 0; i < v.size(); ++i) {
            ans.push_back({v[i].second.first, v[i].second.second});
        }
        return ans;
    }
};
```
['Array', 'Sorting', 'Matrix', 'C++']