給出 R 行 C 列的矩陣,其中的單元格的整數坐標為 (r, c),滿足 0 <= r < R 且 0 <= c < C,
另外,我們在該矩陣中給出了一個坐標為 (r0, c0) 的單元格,
回傳矩陣中的所有單元格的坐標,并按到 (r0, c0) 的距離從最小到最大的順序排,其中,兩單元格(r1, c1) 和 (r2, c2) 之間的距離是曼哈頓距離,|r1 - r2| + |c1 - c2|,(你可以按任何滿足此條件的順序回傳答案,)
示例 1:
輸入:R = 1, C = 2, r0 = 0, c0 = 0
輸出:[[0,0],[0,1]]
解釋:從 (r0, c0) 到其他單元格的距離為:[0,1]
示例 2:
輸入:R = 2, C = 2, r0 = 0, c0 = 1
輸出:[[0,1],[0,0],[1,1],[1,0]]
解釋:從 (r0, c0) 到其他單元格的距離為:[0,1,1,2]
[[0,1],[1,1],[0,0],[1,0]] 也會被視作正確答案,
示例 3:
輸入:R = 2, C = 3, r0 = 1, c0 = 2
輸出:[[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
解釋:從 (r0, c0) 到其他單元格的距離為:[0,1,1,2,2,3]
其他滿足題目要求的答案也會被視為正確,例如 [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]],
提示:
1 <= R <= 100
1 <= C <= 100
0 <= r0 < R
0 <= c0 < C
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/matrix-cells-in-distance-order
著作權歸領扣網路所有,商業轉載請聯系官方授權,非商業轉載請注明出處,
解題思路:
這次又是重寫排序函式,也是lambda的一種c++實作,首先自然是雙重for回圈把數放入陣列中,然后就是排序程序,在sort函式中進行重寫即可,代碼如下:
class Solution {
public:
vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {
vector<vector<int>> res;
vector<int> temp;
for(int i = 0; i < R; i ++){
for(int j = 0; j < C; j ++){
temp.push_back(i);
temp.push_back(j);
res.push_back(temp);
temp.clear();
}
}
sort(res.begin(), res.end(), [=](vector<int>& a, vector<int>&b){
return abs(a[0] - r0) + abs(a[1] - c0) < abs(b[0] - r0) + abs(b[1] - c0);
});
return res;
}
};
/*作者:heroding
鏈接:https://leetcode-cn.com/problems/matrix-cells-in-distance-order/solution/zhong-xie-pai-xu-by-heroding/
來源:力扣(LeetCode)
著作權歸作者所有,商業轉載請聯系作者獲得授權,非商業轉載請注明出處,*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/224274.html
標籤:python
