Matrix Cells in Distance Order
Problem
You are given four integers row
, cols
, rCenter
, and cCenter
. There is a rows x cols
matrix and you are on the cell with the coordinates (rCenter, cCenter)
.
Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter)
from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition.
The distance between two cells (r1, c1)
and (r2, c2)
is |r1 - r2| + |c1 - c2|
.
Constraints
1 <= rows, cols <= 100
0 <= rCenter < rows
0 <= cCenter < cols
Solution
The problem Matrix Cells in Distance Order
can be solved by performing a breadth-first iteration starting from (rCenter, cCenter)
until the entire matrix is iterated. Due to the characteristic of breadth-first it is guaranteed that the points that are closer to the center will get iterated first.
Implementation
typedef pair<int, int> Pair;
static const int fast_io = []()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution
{
public:
vector<vector<int>> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter)
{
bool checked[100][100] = {};
queue<Pair> cells;
cells.push({rCenter, cCenter});
vector<vector<int>> ans;
while (!cells.empty())
{
Pair cell = cells.front();
cells.pop();
if (!((unsigned int)(rows - 1 - cell.first) < rows))
continue;
if (!((unsigned int)(cols - 1 - cell.second) < cols))
continue;
if (checked[cell.first][cell.second])
continue;
ans.push_back({cell.first, cell.second});
checked[cell.first][cell.second] = true;
cells.push({cell.first, cell.second - 1});
cells.push({cell.first, cell.second + 1});
cells.push({cell.first - 1, cell.second});
cells.push({cell.first + 1, cell.second});
}
return ans;
}
};