-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrixDistance.txt
28 lines (22 loc) · 1009 Bytes
/
matrixDistance.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
1030. Matrix Cells in Distance Order
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|.
class Solution {
public:
vector<vector<int>> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
vector<vector<int>> ans;
for(int i = 0 ; i < rows ; i++){
for(int j = 0 ; j < cols ; j++){
ans.push_back({i,j});
}
sort(ans.begin(),ans.end(),[&](auto& a, auto& b){
return (abs(rCenter-a[0]) + abs(cCenter-a[1]) < abs(rCenter-b[0]) + abs(cCenter-b[1]));
});
}
return ans;
}
};