Leetcode 1030. Matrix Cells in Distance Order
You are given four integers rows
, cols
, rCenter
, and cCenter
. There is a rows x cols
matrix and you are sitting in the cell (rCenter, cCenter)
.
Return the matrix cells in the order of their distances from (rCenter, cCenter)
— ordered from the smallest distance to the largest distance. Here, the distance between two cells (r1, c1)
and (r2, c2)
is defined as the Manhattan Distance: |r1 - r2| + |c1 - c2|
.
rows
, cols
, rCenter
, and cCenter
?
1 <= rows, cols <= 100
0 <= rCenter < rows
0 <= cCenter < cols
(rCenter, cCenter)
?
With these clarifications, let’s proceed to the solution.
(rCenter, cCenter)
.#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
vector<vector<int>> cells;
// Generate all cells in the matrix
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
cells.push_back({r, c});
}
}
// Sort cells based on Manhattan distance
sort(cells.begin(), cells.end(), [&](const vector<int>& a, const vector<int>& b) {
int distA = abs(a[0] - rCenter) + abs(a[1] - cCenter);
int distB = abs(b[0] - rCenter) + abs(b[1] - cCenter);
return distA < distB;
});
return cells;
}
};
rows * cols
.Overall, the time complexity is dominated by the sorting step, so it is O((rows * cols) * log(rows * cols)).
Thus, the space complexity is O(rows * cols).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?